@tiangong-lca/foundry 0.1.18 → 0.1.19

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 (84) hide show
  1. package/docs/package-distribution-contract.md +5 -5
  2. package/docs/public-runtime-contract.md +12 -0
  3. package/docs/runtime-context-contract.md +2 -0
  4. package/package-dist/assets/foundry-package-descriptor.json +268 -98
  5. package/package-dist/scripts/foundry-facade.js +3 -0
  6. package/package-dist/scripts/foundry-runtime.d.ts +1 -1
  7. package/package-dist/scripts/lib/decision-owners/identity-preflight.js +3 -1
  8. package/package-dist/scripts/lib/finalize-owners/cli-wrappers.d.ts +72 -1
  9. package/package-dist/scripts/lib/finalize-owners/cli-wrappers.js +123 -3
  10. package/package-dist/scripts/lib/finalize-owners/post-authoring.d.ts +9 -0
  11. package/package-dist/scripts/lib/finalize-owners/post-authoring.js +37 -8
  12. package/package-dist/scripts/lib/foundry-authentication-environment.js +1 -1
  13. package/package-dist/scripts/lib/foundry-curation-queue.d.ts +73 -0
  14. package/package-dist/scripts/lib/foundry-curation-queue.js +261 -0
  15. package/package-dist/scripts/lib/foundry-edge-draft-admission.d.ts +17 -0
  16. package/package-dist/scripts/lib/foundry-edge-draft-admission.js +94 -0
  17. package/package-dist/scripts/lib/foundry-edge-identity-preflight.d.ts +47 -0
  18. package/package-dist/scripts/lib/foundry-edge-identity-preflight.js +268 -0
  19. package/package-dist/scripts/lib/foundry-edge-oauth.d.ts +4 -0
  20. package/package-dist/scripts/lib/foundry-edge-oauth.js +154 -0
  21. package/package-dist/scripts/lib/foundry-edge-reference-intent.d.ts +51 -0
  22. package/package-dist/scripts/lib/foundry-edge-reference-intent.js +184 -0
  23. package/package-dist/scripts/lib/foundry-edge-repair-preparation.d.ts +21 -0
  24. package/package-dist/scripts/lib/foundry-edge-repair-preparation.js +120 -0
  25. package/package-dist/scripts/lib/foundry-edge-session.d.ts +15 -0
  26. package/package-dist/scripts/lib/foundry-edge-session.js +69 -0
  27. package/package-dist/scripts/lib/foundry-edge-support-plan.d.ts +69 -0
  28. package/package-dist/scripts/lib/foundry-edge-support-plan.js +245 -0
  29. package/package-dist/scripts/lib/foundry-edge-support-planning.d.ts +115 -0
  30. package/package-dist/scripts/lib/foundry-edge-support-planning.js +259 -0
  31. package/package-dist/scripts/lib/foundry-edge-support.d.ts +19 -0
  32. package/package-dist/scripts/lib/foundry-edge-support.js +188 -0
  33. package/package-dist/scripts/lib/foundry-execution-admission.d.ts +4 -2
  34. package/package-dist/scripts/lib/foundry-execution-admission.js +24 -2
  35. package/package-dist/scripts/lib/foundry-finalize-edge-identity.d.ts +30 -0
  36. package/package-dist/scripts/lib/foundry-finalize-edge-identity.js +102 -0
  37. package/package-dist/scripts/lib/foundry-finalize-owners.d.ts +1 -0
  38. package/package-dist/scripts/lib/foundry-finalize-owners.js +68 -2
  39. package/package-dist/scripts/lib/foundry-managed-authentication.js +1 -1
  40. package/package-dist/scripts/lib/foundry-owner-execution-store.d.ts +16 -16
  41. package/package-dist/scripts/lib/foundry-owner-execution-store.js +34 -7
  42. package/package-dist/scripts/lib/foundry-owner-readback.d.ts +20 -0
  43. package/package-dist/scripts/lib/foundry-owner-readback.js +42 -0
  44. package/package-dist/scripts/lib/foundry-package-contract.d.ts +2 -2
  45. package/package-dist/scripts/lib/foundry-package-contract.js +2 -2
  46. package/package-dist/scripts/lib/foundry-preparation-cli-validation.js +71 -0
  47. package/package-dist/scripts/lib/foundry-process-mass-balance.d.ts +64 -0
  48. package/package-dist/scripts/lib/foundry-process-mass-balance.js +224 -0
  49. package/package-dist/scripts/lib/foundry-process-qa.d.ts +19 -0
  50. package/package-dist/scripts/lib/foundry-process-qa.js +423 -0
  51. package/package-dist/scripts/lib/foundry-repair-execution.js +13 -2
  52. package/package-dist/scripts/lib/foundry-runtime-environment.d.ts +2 -0
  53. package/package-dist/scripts/lib/foundry-runtime-environment.js +18 -0
  54. package/package-dist/scripts/lib/foundry-runtime-identity.d.ts +1 -0
  55. package/package-dist/scripts/lib/foundry-runtime-identity.js +19 -1
  56. package/package-dist/scripts/lib/foundry-runtime-qualification.js +2 -2
  57. package/package-dist/scripts/lib/foundry-runtime-utils.d.ts +1 -0
  58. package/package-dist/scripts/lib/foundry-runtime-utils.js +1 -1
  59. package/package-dist/scripts/lib/foundry-typed-authoring-patch.d.ts +76 -0
  60. package/package-dist/scripts/lib/foundry-typed-authoring-patch.js +237 -0
  61. package/package-dist/scripts/lib/foundry-typed-context.d.ts +11 -0
  62. package/package-dist/scripts/lib/foundry-typed-context.js +79 -0
  63. package/package-dist/scripts/lib/foundry-typed-flow-qa.d.ts +166 -0
  64. package/package-dist/scripts/lib/foundry-typed-flow-qa.js +226 -0
  65. package/package-dist/scripts/lib/foundry-typed-model-write.d.ts +6 -0
  66. package/package-dist/scripts/lib/foundry-typed-model-write.js +59 -0
  67. package/package-dist/scripts/lib/foundry-workflow-assessment.js +67 -29
  68. package/package-dist/scripts/lib/foundry-workflow-authorization.js +82 -1
  69. package/package-dist/scripts/lib/foundry-workflow-context.js +59 -18
  70. package/package-dist/scripts/lib/foundry-workflow-execution.js +54 -5
  71. package/package-dist/scripts/lib/foundry-workflow-finalize.js +27 -3
  72. package/package-dist/scripts/lib/foundry-workflow-identity-stage.js +202 -161
  73. package/package-dist/scripts/lib/foundry-workflow-identity.js +16 -10
  74. package/package-dist/scripts/lib/foundry-workflow-io.js +27 -6
  75. package/package-dist/scripts/lib/foundry-workflow-reference-verify.js +102 -29
  76. package/package-dist/scripts/lib/foundry-workflow-repair.js +53 -2
  77. package/package-dist/scripts/lib/foundry-workflow-semantic.js +41 -21
  78. package/package-dist/scripts/lib/identity-preflight-proof.d.ts +1 -0
  79. package/package-dist/scripts/lib/identity-preflight-proof.js +19 -12
  80. package/package-dist/scripts/lib/import-curation/internal/context-inputs.js +1 -1
  81. package/package.json +2 -2
  82. package/specs/schemas/foundry-managed-runtime.schema.json +1 -1
  83. package/specs/schemas/foundry-package-descriptor.schema.json +2 -2
  84. package/specs/schemas/runtime-qualification.schema.json +1 -1
@@ -0,0 +1,268 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { FoundryContextError, resolveFoundryOutput, writeFoundryArtifact, } from "./foundry-runtime-context.js";
4
+ import { resolveInstalledTiangongLcaCliPackage } from "./foundry-runtime-utils.js";
5
+ import { createIdentityPreflightBinding, createIdentityPreflightExecutionManifest, sha256Json, sha256Text, parseFreshIntentBoundAuthReceipt, validateBoundExecutionManifest, } from "./identity-preflight-proof.js";
6
+ import { datasetIdentity, datasetRoot, dataSetInformation, } from "./import-curation/internal/dataset-payload.js";
7
+ import { queryFoundryEdgeIdentity } from "./foundry-edge-session.js";
8
+ function invalid() {
9
+ throw new FoundryContextError("edge_identity_evidence_invalid", "The Edge identity evidence does not match the current audited request.");
10
+ }
11
+ function object(value) {
12
+ if (!value || typeof value !== "object" || Array.isArray(value))
13
+ return invalid();
14
+ return value;
15
+ }
16
+ export function validateEdgeIdentityQuery(type, rowValue, requestText) {
17
+ const row = object(rowValue);
18
+ const request = object(JSON.parse(requestText));
19
+ const search = object(request.remote_candidate_search);
20
+ const edge = object(object(row.remote_search).edge_request);
21
+ const endpoint = type === "flow" ? "flow_hybrid_search" : "process_hybrid_search";
22
+ const body = {
23
+ query: search.query,
24
+ ...(search.filter ? { filter: search.filter } : {}),
25
+ match_count: search.limit,
26
+ page_size: search.limit,
27
+ data_source: search.data_source,
28
+ match_threshold: search.match_threshold,
29
+ lexical_weight: search.lexical_weight,
30
+ semantic_weight: search.semantic_weight,
31
+ rrf_k: search.rrf_k,
32
+ };
33
+ if (edge.endpoint !== endpoint ||
34
+ sha256Json(edge.body) !== sha256Json(body) ||
35
+ row.dataset_type !== type ||
36
+ row.request_bytes_sha256 !== sha256Text(requestText) ||
37
+ row.target_sha256 !== sha256Text(JSON.stringify(request.target)) ||
38
+ search.enabled !== true ||
39
+ typeof body.query !== "string" ||
40
+ !body.query.trim() ||
41
+ !Number.isSafeInteger(body.match_count) ||
42
+ Number(body.match_count) < 1 ||
43
+ Number(body.match_count) > 80 ||
44
+ body.data_source !== "tg")
45
+ return invalid();
46
+ const target = datasetIdentity(request.target, 0, type);
47
+ if (target.id !== row.dataset_id || target.version !== row.dataset_version)
48
+ return invalid();
49
+ return { endpoint, body, target };
50
+ }
51
+ export function edgeIdentityCandidates(type, result, limit) {
52
+ const rows = Array.isArray(result) ? result : object(result).data;
53
+ if (!Array.isArray(rows) || rows.length > limit)
54
+ return invalid();
55
+ const keys = new Set();
56
+ return rows.map((value) => {
57
+ const row = object(value);
58
+ const id = row.id;
59
+ const version = row.version;
60
+ const json = row.json_ordered ?? row.json;
61
+ if (typeof id !== "string" ||
62
+ typeof version !== "string" ||
63
+ !/^\d{2}\.\d{2}\.\d{3}$/u.test(version))
64
+ return invalid();
65
+ const key = `${id}@${version}`;
66
+ if (keys.has(key))
67
+ return invalid();
68
+ keys.add(key);
69
+ const content = object(json);
70
+ const root = datasetRoot(content, type);
71
+ const ownership = object(object(root.administrativeInformation).publicationAndOwnership);
72
+ if (dataSetInformation(root, type)["common:UUID"] !== id ||
73
+ ownership["common:dataSetVersion"] !== version)
74
+ return invalid();
75
+ return { id, version, content, score: row.combined_score ?? row.score ?? null };
76
+ });
77
+ }
78
+ function bindingForEdgeObservation(type, row, requestText, receipt, observation, claim) {
79
+ const { endpoint, target } = validateEdgeIdentityQuery(type, row, requestText);
80
+ const cli = resolveInstalledTiangongLcaCliPackage();
81
+ return createIdentityPreflightBinding({
82
+ datasetType: type,
83
+ datasetId: target.id,
84
+ datasetVersion: target.version,
85
+ targetSha256: String(row.target_sha256),
86
+ requestText,
87
+ semanticArgv: ["edge", "POST", endpoint],
88
+ cli: {
89
+ packageName: cli.packageName,
90
+ packageVersion: cli.packageVersion,
91
+ packageIntegrity: null,
92
+ },
93
+ authReceipt: receipt,
94
+ relevantInputHashes: {
95
+ edge_observation: sha256Json(observation),
96
+ ...(claim
97
+ ? { explicit_dispatch: claim.dispatchSha256, source_file: claim.sourceSha256 }
98
+ : {}),
99
+ },
100
+ });
101
+ }
102
+ /** Run the already-audited bounded query and hand the decision to Foundry's existing review lane. */
103
+ export async function runFoundryEdgeIdentityPreflight(context, qualified, authentication, type, indexFile, outDir, claim) {
104
+ const index = fs.readFileSync(resolveFoundryOutput(context, indexFile), "utf8");
105
+ const rows = index
106
+ .split("\n")
107
+ .filter((line) => line.trim())
108
+ .map((line) => object(JSON.parse(line)));
109
+ if (!rows.length || (claim && rows.length !== 1))
110
+ return invalid();
111
+ const results = [];
112
+ for (const row of rows) {
113
+ const file = (value) => {
114
+ if (typeof value !== "string")
115
+ return invalid();
116
+ return resolveFoundryOutput(context, path.resolve(context.assetRoot, value));
117
+ };
118
+ const requestFile = file(row.request_file);
119
+ const reportFile = file(row.expected_report_file);
120
+ const requestText = fs.readFileSync(requestFile, "utf8");
121
+ const { endpoint, body, target } = validateEdgeIdentityQuery(type, row, requestText);
122
+ const { receipt, result } = await queryFoundryEdgeIdentity(context, qualified, authentication, endpoint, body);
123
+ if (fs.readFileSync(requestFile, "utf8") !== requestText)
124
+ return invalid();
125
+ const candidates = edgeIdentityCandidates(type, result, Number(body.match_count));
126
+ const candidateFile = path.join(path.dirname(reportFile), "edge-search-observation.json");
127
+ const observation = {
128
+ schema: "tiangong-foundry.edge-identity-observation.v1",
129
+ endpoint,
130
+ project_ref: receipt.project.project_ref,
131
+ user_id: receipt.identity.user_id,
132
+ query: body,
133
+ ...(claim ? { verified_actor_receipt: receipt } : {}),
134
+ result,
135
+ };
136
+ writeFoundryArtifact(context, candidateFile, JSON.stringify(observation, null, 2) + "\n");
137
+ const binding = bindingForEdgeObservation(type, row, requestText, claim?.receipt ?? receipt, observation, claim);
138
+ const report = {
139
+ schema: "tiangong-foundry.edge-identity-decision.v1",
140
+ producer: "foundry",
141
+ status: "needs_review",
142
+ decision: "manual_review",
143
+ next_action: "queue_manual_review",
144
+ target: { id: target.id, version: target.version },
145
+ candidates,
146
+ candidate_sources: [
147
+ {
148
+ kind: "remote_search",
149
+ endpoint,
150
+ path: candidateFile,
151
+ query: body.query,
152
+ row_count: candidates.length,
153
+ bounded: true,
154
+ },
155
+ ],
156
+ findings: [],
157
+ blockers: [],
158
+ };
159
+ const reportText = JSON.stringify(report, null, 2) + "\n";
160
+ writeFoundryArtifact(context, reportFile, reportText);
161
+ const manifest = createIdentityPreflightExecutionManifest(binding, reportText, new Date().toISOString());
162
+ const manifestFile = path.join(path.dirname(reportFile), "foundry-identity-preflight-execution.json");
163
+ writeFoundryArtifact(context, manifestFile, JSON.stringify(manifest, null, 2) + "\n");
164
+ const { command_spec: _legacyCommand, ...rest } = row;
165
+ results.push({
166
+ ...rest,
167
+ command: `POST ${endpoint}`,
168
+ execution_manifest_file: manifestFile,
169
+ expected_project_ref: receipt.project.project_ref,
170
+ expected_user_id: receipt.identity.user_id,
171
+ });
172
+ }
173
+ const completedIndex = path.join(outDir, "identity-preflight-requests.jsonl");
174
+ writeFoundryArtifact(context, completedIndex, results.map((row) => JSON.stringify(row)).join("\n") + "\n");
175
+ const reportFile = path.join(outDir, "dataset-identity-preflight-run-report.json");
176
+ const report = {
177
+ schema: "tiangong-foundry.edge-identity-preflight.v1",
178
+ status: "completed_with_identity_findings",
179
+ producer: "foundry",
180
+ index: completedIndex,
181
+ files: { report: reportFile },
182
+ };
183
+ writeFoundryArtifact(context, reportFile, JSON.stringify(report, null, 2) + "\n");
184
+ return report;
185
+ }
186
+ /** Adopt one original Edge observation only when the persisted dispatch and all response evidence agree. */
187
+ export function readRetainedFoundryEdgeIdentity(context, type, row, runDir, mode, claim) {
188
+ const file = (value) => {
189
+ if (typeof value !== "string")
190
+ return invalid();
191
+ return resolveFoundryOutput(context, path.resolve(context.assetRoot, value));
192
+ };
193
+ const read = (name) => {
194
+ const stat = fs.lstatSync(name);
195
+ if (!stat.isFile() || stat.size > 8 * 1024 * 1024)
196
+ return invalid();
197
+ return fs.readFileSync(name, "utf8");
198
+ };
199
+ const runFile = file(path.join(runDir, "dataset-identity-preflight-run-report.json"));
200
+ const index = file(path.join(runDir, "identity-preflight-requests.jsonl"));
201
+ const run = object(JSON.parse(read(runFile)));
202
+ const completedRows = read(index).trimEnd().split("\n");
203
+ if (run.schema !== "tiangong-foundry.edge-identity-preflight.v1" ||
204
+ run.producer !== "foundry" ||
205
+ run.status !== "completed_with_identity_findings" ||
206
+ run.index !== index ||
207
+ object(run.files).report !== runFile ||
208
+ completedRows.length !== 1)
209
+ return invalid();
210
+ const requestText = read(file(row.request_file));
211
+ const { endpoint, body, target } = validateEdgeIdentityQuery(type, row, requestText);
212
+ const reportFile = file(row.expected_report_file);
213
+ const directory = path.dirname(reportFile);
214
+ const candidateFile = file(path.join(directory, "edge-search-observation.json"));
215
+ const manifestFile = file(path.join(directory, "foundry-identity-preflight-execution.json"));
216
+ const observation = object(JSON.parse(read(candidateFile)));
217
+ const reportText = read(reportFile);
218
+ const report = object(JSON.parse(reportText));
219
+ const manifest = object(JSON.parse(read(manifestFile)));
220
+ const checkedAt = Date.parse(String(manifest.completed_at_utc));
221
+ const claimedAt = Date.parse(claim.claimedAt);
222
+ const actor = parseFreshIntentBoundAuthReceipt(observation.verified_actor_receipt, {
223
+ nowMs: checkedAt,
224
+ maxAgeMs: 60_000,
225
+ expectedProjectRef: claim.receipt.project.project_ref,
226
+ expectedUserId: claim.receipt.identity.user_id,
227
+ sessionMode: mode,
228
+ });
229
+ const { command_spec: _legacyCommand, ...rest } = row;
230
+ const completed = object(JSON.parse(completedRows[0]));
231
+ const expected = {
232
+ ...rest,
233
+ command: `POST ${endpoint}`,
234
+ execution_manifest_file: manifestFile,
235
+ expected_project_ref: actor.project.project_ref,
236
+ expected_user_id: actor.identity.user_id,
237
+ };
238
+ const candidates = edgeIdentityCandidates(type, observation.result, Number(body.match_count));
239
+ const source = Array.isArray(report.candidate_sources) && report.candidate_sources.length === 1
240
+ ? object(report.candidate_sources[0])
241
+ : invalid();
242
+ const binding = bindingForEdgeObservation(type, row, requestText, claim.receipt, observation, claim);
243
+ if (observation.schema !== "tiangong-foundry.edge-identity-observation.v1" ||
244
+ observation.endpoint !== endpoint ||
245
+ observation.project_ref !== actor.project.project_ref ||
246
+ observation.user_id !== actor.identity.user_id ||
247
+ sha256Json(actor.cli) !== sha256Json(claim.receipt.cli) ||
248
+ actor.project.project_base_url !== claim.receipt.project.project_base_url ||
249
+ sha256Json(observation.query) !== sha256Json(body) ||
250
+ !Number.isFinite(claimedAt) ||
251
+ checkedAt < claimedAt ||
252
+ Date.parse(actor.captured_at_utc) < claimedAt - 5_000 ||
253
+ sha256Json(completed) !== sha256Json(expected) ||
254
+ report.schema !== "tiangong-foundry.edge-identity-decision.v1" ||
255
+ report.producer !== "foundry" ||
256
+ report.decision !== "manual_review" ||
257
+ report.status !== "needs_review" ||
258
+ object(report.target).id !== target.id ||
259
+ object(report.target).version !== target.version ||
260
+ sha256Json(report.candidates) !== sha256Json(candidates) ||
261
+ source.endpoint !== endpoint ||
262
+ source.path !== candidateFile ||
263
+ source.row_count !== candidates.length ||
264
+ source.bounded !== true ||
265
+ !validateBoundExecutionManifest(manifest, binding, reportText).ok)
266
+ return invalid();
267
+ return { run, row: completed };
268
+ }
@@ -0,0 +1,4 @@
1
+ import type { FoundryPublicOAuthConfiguration } from "./foundry-authentication-environment.ts";
2
+ type OpenBrowser = (url: string) => Promise<void>;
3
+ export declare function resolveFoundryEdgeOAuth(origin: string, expectedUser: string, configuration: FoundryPublicOAuthConfiguration, openBrowser?: OpenBrowser): Promise<string>;
4
+ export {};
@@ -0,0 +1,154 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import { createServer } from "node:http";
4
+ import { FoundryContextError } from "./foundry-runtime-context.js";
5
+ // The existing public TianGong CLI registration used by the released CLI 0.4.0.
6
+ const officialOrigin = "https://qgzvkongdjqiiamzbbts.supabase.co";
7
+ const officialClient = "1837c6d3-3c9d-48e0-bbf7-b532b78f9f76";
8
+ const defaultCallback = "http://127.0.0.1:49191/oauth/callback";
9
+ const inMemory = new Map();
10
+ function fail(code, message) {
11
+ throw new FoundryContextError(code, message);
12
+ }
13
+ function browser(url) {
14
+ const windows = process.platform === "win32";
15
+ const command = windows ? "rundll32.exe" : process.platform === "darwin" ? "open" : "xdg-open";
16
+ const args = windows ? ["url.dll,FileProtocolHandler", url] : [url];
17
+ return new Promise((resolve, reject) => {
18
+ const child = spawn(command, args, {
19
+ detached: true,
20
+ shell: false,
21
+ stdio: "ignore",
22
+ windowsHide: true,
23
+ });
24
+ child.once("error", () => reject(new FoundryContextError("edge_oauth_browser_failed", "Open the OAuth authorization in an available system browser.")));
25
+ child.once("spawn", () => {
26
+ child.unref();
27
+ resolve();
28
+ });
29
+ });
30
+ }
31
+ function clientSettings(origin, configuration) {
32
+ const clientId = configuration.oauthClientId || (origin === officialOrigin ? officialClient : "");
33
+ const redirect = new URL(configuration.oauthRedirectUri || defaultCallback);
34
+ if (!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/iu.test(clientId) ||
35
+ redirect.protocol !== "http:" ||
36
+ redirect.hostname !== "127.0.0.1" ||
37
+ Number(redirect.port) < 1024 ||
38
+ redirect.username ||
39
+ redirect.password ||
40
+ redirect.search ||
41
+ redirect.hash ||
42
+ redirect.pathname !== "/oauth/callback")
43
+ return fail("edge_oauth_config_invalid", "OAuth requires the selected project's public client and its registered loopback redirect.");
44
+ return { origin, clientId, redirect };
45
+ }
46
+ async function authorize(client, openBrowser) {
47
+ const state = randomBytes(32).toString("base64url");
48
+ const verifier = randomBytes(48).toString("base64url");
49
+ const authorization = new URL("/auth/v1/oauth/authorize", client.origin);
50
+ authorization.search = new URLSearchParams({
51
+ response_type: "code",
52
+ client_id: client.clientId,
53
+ redirect_uri: client.redirect.href,
54
+ scope: "openid email profile",
55
+ code_challenge_method: "S256",
56
+ code_challenge: createHash("sha256").update(verifier).digest("base64url"),
57
+ state,
58
+ }).toString();
59
+ return new Promise((resolve, reject) => {
60
+ let settled = false;
61
+ const finish = (error, code) => {
62
+ if (settled)
63
+ return;
64
+ settled = true;
65
+ clearTimeout(timeout);
66
+ server.closeAllConnections();
67
+ server.close();
68
+ if (error)
69
+ reject(error);
70
+ else
71
+ resolve({ code: code, verifier });
72
+ };
73
+ const server = createServer((request, response) => {
74
+ const url = new URL(request.url ?? "/", client.redirect.origin);
75
+ if (request.method !== "GET" ||
76
+ request.headers.host !== client.redirect.host ||
77
+ url.origin !== client.redirect.origin ||
78
+ url.pathname !== client.redirect.pathname ||
79
+ url.searchParams.getAll("state").length !== 1 ||
80
+ url.searchParams.get("state") !== state) {
81
+ response.writeHead(400, { "Cache-Control": "no-store" }).end("Invalid OAuth callback.");
82
+ return;
83
+ }
84
+ const code = url.searchParams.get("code");
85
+ if (!code ||
86
+ code.length > 4096 ||
87
+ url.searchParams.getAll("code").length !== 1 ||
88
+ url.searchParams.has("error")) {
89
+ response
90
+ .writeHead(400, { "Cache-Control": "no-store" })
91
+ .end("Authorization was not completed.", () => finish(new FoundryContextError("edge_oauth_not_authorized", "The operator did not authorize the Edge session.")));
92
+ return;
93
+ }
94
+ response
95
+ .writeHead(200, {
96
+ "Cache-Control": "no-store",
97
+ "Content-Type": "text/plain; charset=utf-8",
98
+ })
99
+ .end("Foundry received authorization. You can close this tab.", () => finish(null, code));
100
+ });
101
+ const timeout = setTimeout(() => finish(new FoundryContextError("edge_oauth_timeout", "The loopback OAuth authorization expired.")), 120_000);
102
+ server.once("error", () => finish(new FoundryContextError("edge_oauth_callback_unavailable", "The registered loopback OAuth port is unavailable.")));
103
+ server.listen(Number(client.redirect.port), "127.0.0.1", () => void openBrowser(authorization.href).catch((error) => finish(error)));
104
+ });
105
+ }
106
+ function object(value) {
107
+ return value && typeof value === "object" && !Array.isArray(value)
108
+ ? value
109
+ : {};
110
+ }
111
+ export async function resolveFoundryEdgeOAuth(origin, expectedUser, configuration, openBrowser = browser) {
112
+ if (new URL(origin).protocol !== "https:")
113
+ return fail("edge_oauth_config_invalid", "Use an HTTPS project for operator OAuth.");
114
+ const client = clientSettings(origin, configuration);
115
+ const key = JSON.stringify([origin, client.clientId, expectedUser]);
116
+ let selected = inMemory.get(key);
117
+ if (!selected || selected.expiresAt - Date.now() < 90_000) {
118
+ const { code, verifier } = await authorize(client, openBrowser);
119
+ const response = await fetch(new URL("/auth/v1/oauth/token", origin), {
120
+ method: "POST",
121
+ headers: { Accept: "application/json", "Content-Type": "application/x-www-form-urlencoded" },
122
+ body: new URLSearchParams({
123
+ grant_type: "authorization_code",
124
+ client_id: client.clientId,
125
+ redirect_uri: client.redirect.href,
126
+ code,
127
+ code_verifier: verifier,
128
+ }),
129
+ redirect: "error",
130
+ signal: AbortSignal.timeout(15_000),
131
+ });
132
+ if (!response.ok)
133
+ return fail("edge_oauth_token_failed", "The existing OAuth service did not issue an operator session.");
134
+ const body = object(await response.json());
135
+ if (typeof body.access_token !== "string" ||
136
+ !body.access_token ||
137
+ String(body.token_type).toLowerCase() !== "bearer" ||
138
+ !Number.isSafeInteger(body.expires_in) ||
139
+ Number(body.expires_in) <= 0)
140
+ return fail("edge_oauth_token_invalid", "OAuth returned an invalid operator session.");
141
+ selected = { token: body.access_token, expiresAt: Date.now() + Number(body.expires_in) * 1000 };
142
+ }
143
+ const response = await fetch(new URL("/auth/v1/oauth/userinfo", origin), {
144
+ headers: { Accept: "application/json", Authorization: `Bearer ${selected.token}` },
145
+ redirect: "error",
146
+ signal: AbortSignal.timeout(15_000),
147
+ });
148
+ if (!response.ok || object(await response.json()).sub !== expectedUser) {
149
+ inMemory.delete(key);
150
+ return fail("edge_oauth_actor_mismatch", "The browser session does not match the verified task account.");
151
+ }
152
+ inMemory.set(key, selected);
153
+ return selected.token;
154
+ }
@@ -0,0 +1,51 @@
1
+ import { type FoundryInputFact, type FoundryRuntimeContext } from "./foundry-runtime-context.ts";
2
+ import { type BundleRowType } from "./bundle-row-types.ts";
3
+ export type EdgeReferenceSnapshot = {
4
+ table: string;
5
+ id: string;
6
+ version: string;
7
+ payload_sha256: string;
8
+ user_id: string;
9
+ state_code: 0 | 100;
10
+ };
11
+ export declare function edgeReferenceKey(reference: {
12
+ table: string;
13
+ id: string;
14
+ version: string;
15
+ }): string;
16
+ export declare function readEdgeReferenceSnapshot(value: unknown, actor: string): EdgeReferenceSnapshot;
17
+ export declare function readEdgeReferenceIntent(context: FoundryRuntimeContext, input: string, type: BundleRowType, target: {
18
+ project_ref: string;
19
+ user_id: string;
20
+ }, rows: unknown[]): {
21
+ binding: {
22
+ file: {
23
+ path: string;
24
+ sha256: string;
25
+ bytes: number;
26
+ };
27
+ project_ref: string;
28
+ actor_user_id: string;
29
+ consumers: {
30
+ row_index: number;
31
+ table: string;
32
+ id: string;
33
+ version: string;
34
+ payload_sha256: string;
35
+ }[];
36
+ references: {
37
+ row_index: number;
38
+ path: string;
39
+ selected: EdgeReferenceSnapshot;
40
+ review: {
41
+ file: FoundryInputFact;
42
+ latest: EdgeReferenceSnapshot;
43
+ };
44
+ }[];
45
+ review_files: FoundryInputFact[];
46
+ };
47
+ reviewed: Map<string, {
48
+ selected: EdgeReferenceSnapshot;
49
+ latest: EdgeReferenceSnapshot;
50
+ }>;
51
+ };
@@ -0,0 +1,184 @@
1
+ import path from "node:path";
2
+ import { FoundryContextError, readFoundryInput, resolveFoundryInputPath, } from "./foundry-runtime-context.js";
3
+ import { bundleRowTypes } from "./bundle-row-types.js";
4
+ import { datasetIdentity } from "./import-curation/internal/dataset-payload.js";
5
+ import { collectDatasetReferences } from "./import-curation/internal/workflow-reference-closure.js";
6
+ import { sha256Json } from "./identity-preflight-proof.js";
7
+ const uuid = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/iu;
8
+ const version = /^\d{2}\.\d{2}\.\d{3}$/u;
9
+ const digest = /^[0-9a-f]{64}$/u;
10
+ const maximumFileBytes = 8 * 1024 * 1024;
11
+ export function edgeReferenceKey(reference) {
12
+ return `${reference.table}:${reference.id}@${reference.version}`;
13
+ }
14
+ function requireIntent(value, message) {
15
+ if (!value)
16
+ throw new FoundryContextError("edge_reference_intent_invalid", message);
17
+ }
18
+ function record(value, keys) {
19
+ requireIntent(value &&
20
+ typeof value === "object" &&
21
+ !Array.isArray(value) &&
22
+ Object.keys(value).length === keys.length &&
23
+ keys.every((key) => Object.hasOwn(value, key)), "Reference intent or review contains missing or unsupported fields.");
24
+ return value;
25
+ }
26
+ export function readEdgeReferenceSnapshot(value, actor) {
27
+ const snapshot = record(value, [
28
+ "table",
29
+ "id",
30
+ "version",
31
+ "payload_sha256",
32
+ "user_id",
33
+ "state_code",
34
+ ]);
35
+ requireIntent(typeof snapshot.table === "string" &&
36
+ typeof snapshot.id === "string" &&
37
+ uuid.test(snapshot.id) &&
38
+ typeof snapshot.version === "string" &&
39
+ version.test(snapshot.version) &&
40
+ typeof snapshot.payload_sha256 === "string" &&
41
+ digest.test(snapshot.payload_sha256) &&
42
+ typeof snapshot.user_id === "string" &&
43
+ uuid.test(snapshot.user_id) &&
44
+ (snapshot.state_code === 100 ||
45
+ (snapshot.state_code === 0 && snapshot.user_id.toLowerCase() === actor)), "A reviewed reference must select exact content of a public version or own draft.");
46
+ return {
47
+ table: snapshot.table,
48
+ id: snapshot.id.toLowerCase(),
49
+ version: snapshot.version,
50
+ payload_sha256: snapshot.payload_sha256,
51
+ user_id: snapshot.user_id.toLowerCase(),
52
+ state_code: snapshot.state_code,
53
+ };
54
+ }
55
+ export function readEdgeReferenceIntent(context, input, type, target, rows) {
56
+ const read = (inputPath) => {
57
+ const selected = resolveFoundryInputPath(context, inputPath);
58
+ const bytes = readFoundryInput(context, selected, maximumFileBytes);
59
+ const fact = context.inputs.find((item) => item.path === selected);
60
+ const file = { path: fact.path, sha256: fact.sha256, bytes: fact.bytes };
61
+ try {
62
+ const value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
63
+ return { file, value };
64
+ }
65
+ catch {
66
+ throw new FoundryContextError("edge_reference_intent_invalid", "Reference evidence must be UTF-8 JSON.");
67
+ }
68
+ };
69
+ const { file, value } = read(input);
70
+ const intent = record(value, [
71
+ "schema_version",
72
+ "project_ref",
73
+ "actor_user_id",
74
+ "consumers",
75
+ "references",
76
+ ]);
77
+ const identities = rows.map((row, index) => datasetIdentity(row, index, type));
78
+ const consumers = identities.map(({ id, version, payload }, row_index) => ({
79
+ row_index,
80
+ table: bundleRowTypes[type].plural,
81
+ id,
82
+ version,
83
+ payload_sha256: sha256Json(payload),
84
+ }));
85
+ requireIntent(intent.schema_version === "dataset-exact-reference-intent.v1" &&
86
+ /^[a-z0-9]{20}$/u.test(target.project_ref) &&
87
+ intent.project_ref === target.project_ref &&
88
+ typeof intent.actor_user_id === "string" &&
89
+ intent.actor_user_id.toLowerCase() === target.user_id &&
90
+ consumers.length > 0 &&
91
+ Array.isArray(intent.consumers) &&
92
+ sha256Json(intent.consumers.map((raw) => {
93
+ const row = record(raw, ["row_index", "table", "id", "version", "payload_sha256"]);
94
+ requireIntent(typeof row.id === "string" && uuid.test(row.id), "Reference consumer UUID is invalid.");
95
+ return { ...row, id: row.id.toLowerCase() };
96
+ })) === sha256Json(consumers) &&
97
+ Array.isArray(intent.references) &&
98
+ intent.references.length > 0 &&
99
+ intent.references.length <= 10000, "Reference intent must bind the verified actor and every exact final consumer in order.");
100
+ const occurrences = identities.map(({ payload }) => collectDatasetReferences(payload));
101
+ const selectedOccurrences = new Set();
102
+ const reviewFiles = new Map();
103
+ const reviewed = new Map();
104
+ let bytes = file.bytes;
105
+ const references = intent.references.map((raw) => {
106
+ const entry = record(raw, ["row_index", "path", "selected", "review"]);
107
+ const selected = readEdgeReferenceSnapshot(entry.selected, target.user_id);
108
+ const row_index = Number(entry.row_index);
109
+ const pointer = entry.path;
110
+ const occurrence = `${row_index}:${String(pointer)}`;
111
+ requireIntent(typeof entry.row_index === "number" &&
112
+ Number.isInteger(row_index) &&
113
+ typeof pointer === "string" &&
114
+ pointer.startsWith("/") &&
115
+ pointer.trim() === pointer &&
116
+ !selectedOccurrences.has(occurrence) &&
117
+ occurrences[row_index]?.filter((ref) => ref.path === pointer &&
118
+ ref.table === selected.table &&
119
+ ref.id === selected.id &&
120
+ ref.version === selected.version).length === 1, "Review must identify one unchanged exact occurrence in the selected consumer.");
121
+ selectedOccurrences.add(occurrence);
122
+ const locator = record(entry.review, ["file", "sha256"]);
123
+ requireIntent(typeof locator.file === "string" &&
124
+ locator.file.length > 0 &&
125
+ locator.file.trim() === locator.file &&
126
+ !/[\0\r\n]/u.test(locator.file), "Review locator must preserve its exact file spelling.");
127
+ const reviewPath = resolveFoundryInputPath(context, path.resolve(path.dirname(file.path), locator.file));
128
+ let review = reviewFiles.get(reviewPath);
129
+ if (!review) {
130
+ review = read(reviewPath);
131
+ bytes += review.file.bytes;
132
+ requireIntent(bytes <= 64 * 1024 * 1024, "Reference evidence exceeds its content budget.");
133
+ reviewFiles.set(reviewPath, review);
134
+ }
135
+ const declared = record(review.value, [
136
+ "schema_version",
137
+ "decision",
138
+ "reason",
139
+ "selected",
140
+ "latest",
141
+ ]);
142
+ const latest = readEdgeReferenceSnapshot(declared.latest, target.user_id);
143
+ const key = edgeReferenceKey(selected);
144
+ const snapshots = { selected, latest };
145
+ requireIntent(locator.sha256 === review.file.sha256 &&
146
+ declared.schema_version === "dataset-exact-reference-review.v1" &&
147
+ declared.decision === "use_selected_exact" &&
148
+ typeof declared.reason === "string" &&
149
+ declared.reason.trim() &&
150
+ declared.reason.length <= 8192 &&
151
+ sha256Json(readEdgeReferenceSnapshot(declared.selected, target.user_id)) ===
152
+ sha256Json(selected) &&
153
+ latest.table === selected.table &&
154
+ latest.id === selected.id &&
155
+ latest.version >= selected.version &&
156
+ (latest.version !== selected.version || sha256Json(latest) === sha256Json(selected)) &&
157
+ (!reviewed.has(key) || sha256Json(reviewed.get(key)) === sha256Json(snapshots)), "Review must bind unchanged selected bytes and a consistent reviewed latest version.");
158
+ reviewed.set(key, snapshots);
159
+ return { row_index, path: pointer, selected, review: { file: review.file, latest } };
160
+ });
161
+ // One remote observation covers identical exact dependencies. Every outdated occurrence still
162
+ // requires its own explicit review before that observation can authorize the older version.
163
+ occurrences.forEach((list, index) => {
164
+ for (const ref of list) {
165
+ if (!ref.table)
166
+ continue;
167
+ const review = reviewed.get(edgeReferenceKey({ ...ref, table: ref.table }));
168
+ requireIntent(!review ||
169
+ review.selected.version === review.latest.version ||
170
+ selectedOccurrences.has(`${index}:${ref.path}`), "Every occurrence of an outdated exact dependency requires its own explicit review.");
171
+ }
172
+ });
173
+ return {
174
+ binding: {
175
+ file,
176
+ project_ref: target.project_ref,
177
+ actor_user_id: target.user_id,
178
+ consumers,
179
+ references,
180
+ review_files: [...reviewFiles.values()].map((item) => item.file),
181
+ },
182
+ reviewed,
183
+ };
184
+ }