@clavis.nexus/setup 3.0.1 → 3.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -259,6 +259,91 @@ type SetupClient = {
259
259
  accepted_regions: AppRegion[] | null;
260
260
  unchanged?: true;
261
261
  }>>;
262
+ /**
263
+ * Have Clavis take a snapshot of the org's terms or privacy notice, from the app's confirmed host or the org's
264
+ * domain. The agreement profile names the document by the snapshot's SHA-256
265
+ */
266
+ appLexDocument(args: {
267
+ orgId: string;
268
+ appId: string;
269
+ url: string;
270
+ }): Promise<SetupResult<Record<string, unknown>>>;
271
+ /**
272
+ * Set the app's agreement profile (what Connect shows when the app asks for an agreement), or clear it with null,
273
+ * with a passkey. Clavis reads and normalises the profile, and tells this tool what to sign
274
+ */
275
+ appLexProfileSet(args: {
276
+ orgId: string;
277
+ appId: string;
278
+ profile: unknown;
279
+ }): Promise<SetupResult<{
280
+ app_id: string;
281
+ lex_profile: unknown;
282
+ }>>;
283
+ /** How many agreement decisions a query matches, by outcome, stop reason and pack */
284
+ lexCounts(args: {
285
+ orgId: string;
286
+ query?: unknown;
287
+ }): Promise<SetupResult<Record<string, unknown>>>;
288
+ /**
289
+ * Start an export of agreement decisions. Many people's decisions (`kind: "decisions"`) need an owner's or admin's
290
+ * passkey over the request; one person's (`kind: "subject"`) does not
291
+ */
292
+ lexExport(args: {
293
+ orgId: string;
294
+ request: unknown;
295
+ }): Promise<SetupResult<{
296
+ job: Record<string, unknown>;
297
+ }>>;
298
+ lexExports(args: {
299
+ orgId: string;
300
+ }): Promise<SetupResult<{
301
+ jobs: unknown[];
302
+ }>>;
303
+ lexExportStatus(args: {
304
+ orgId: string;
305
+ jobId: string;
306
+ }): Promise<SetupResult<{
307
+ job: Record<string, unknown>;
308
+ anchor?: unknown;
309
+ }>>;
310
+ /**
311
+ * Fetch a finished export into `dir/<jobId>/` (files at mode 0600: they hold people's records), checking each file
312
+ * against the manifest's digest and the manifest against the digest in the authenticated status
313
+ */
314
+ lexExportDownload(args: {
315
+ orgId: string;
316
+ jobId: string;
317
+ dir: string;
318
+ }): Promise<SetupResult<{
319
+ dir: string;
320
+ manifest_digest: string;
321
+ files: {
322
+ path: string;
323
+ bytes: number;
324
+ }[];
325
+ }>>;
326
+ /** One agreement decision: its record, its ledger proof and where it stands now (`lifecycle`) */
327
+ lexDecision(args: {
328
+ orgId: string;
329
+ decisionId: string;
330
+ }): Promise<SetupResult<Record<string, unknown>>>;
331
+ /** Every agreement decision the org holds for one person (their ID in the org's apps), to answer that person's request */
332
+ lexSubjectDecisions(args: {
333
+ orgId: string;
334
+ subject: string;
335
+ }): Promise<SetupResult<Record<string, unknown>>>;
336
+ /**
337
+ * Erase one person's agreement decisions now, with an owner's or admin's passkey: the org's instruction, for that
338
+ * person's erasure request. The ledger leaves stay and no longer lead to anything. It cannot be undone
339
+ */
340
+ lexSubjectErase(args: {
341
+ orgId: string;
342
+ subject: string;
343
+ }): Promise<SetupResult<{
344
+ erased: number;
345
+ decision_ids: string[];
346
+ }>>;
262
347
  emitEnv(args: {
263
348
  appId: string;
264
349
  operatePrivateJwkJson?: string;
@@ -290,4 +375,5 @@ type OperateKeyPair = {
290
375
  };
291
376
  declare function generateOperateKeyPair(): Promise<OperateKeyPair>;
292
377
 
293
- export { APP_REGIONS, type AppRegion, type CardCheckoutOptions, type CreateSetupClientOptions, DEFAULT_ORIGINS, type DevelopersSession, type HumanAction, type NeedsHuman, type OrgCreationTerms, type Receipt, SetupApiError, type SetupClient, type SetupOrigins, type SetupResult, type SetupStatusReport, clearSession, createSetupClient, defaultSessionPath, formatEnvExport, generateOperateKeyPair, loadSession, originsFromEnv, saveSession };
378
+ export { APP_REGIONS, DEFAULT_ORIGINS, SetupApiError, clearSession, createSetupClient, defaultSessionPath, formatEnvExport, generateOperateKeyPair, loadSession, originsFromEnv, saveSession };
379
+ export type { AppRegion, CardCheckoutOptions, CreateSetupClientOptions, DevelopersSession, HumanAction, NeedsHuman, OrgCreationTerms, Receipt, SetupClient, SetupOrigins, SetupResult, SetupStatusReport };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { execFile } from 'child_process';
2
2
  import { promisify } from 'util';
3
- import { readFile, unlink, mkdir, writeFile, chmod, lstat } from 'fs/promises';
3
+ import { readFile, unlink, mkdir, mkdtemp, writeFile, rename, rm, chmod, lstat } from 'fs/promises';
4
4
  import path, { join, dirname, resolve, relative, isAbsolute } from 'path';
5
5
  import { homedir } from 'os';
6
6
  import { generateKeyPair, exportJWK, jwtVerify, importJWK } from 'jose';
@@ -178,6 +178,71 @@ async function checkTrustRoot(apiOrigin, trustRootJson) {
178
178
  await createVerifier({ trustRoot: trustRootJson, apiOrigin }).trust();
179
179
  return JSON.stringify(JSON.parse(trustRootJson));
180
180
  }
181
+ async function postAppLexDocument(apiOrigin, bearer, orgId, appId, url) {
182
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/lex-documents`, {
183
+ method: "POST",
184
+ bearer,
185
+ body: { url }
186
+ });
187
+ }
188
+ async function postAppLexProfileStatement(apiOrigin, bearer, orgId, appId, profile) {
189
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/lex-profile/statement`, {
190
+ method: "POST",
191
+ bearer,
192
+ body: { profile }
193
+ });
194
+ }
195
+ async function putAppLexProfile(apiOrigin, bearer, orgId, appId, args) {
196
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/apps/${encodeURIComponent(appId)}/lex-profile`, {
197
+ method: "PUT",
198
+ bearer,
199
+ body: { profile: args.profile, receipt: args.receipt }
200
+ });
201
+ }
202
+ async function postLexDecisionCounts(apiOrigin, bearer, orgId, query) {
203
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/lex/decisions/counts`, { method: "POST", bearer, body: { query } });
204
+ }
205
+ async function postLexExportStatement(apiOrigin, bearer, orgId, request) {
206
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/lex/exports/statement`, { method: "POST", bearer, body: { request } });
207
+ }
208
+ async function postLexExport(apiOrigin, bearer, orgId, args) {
209
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/lex/exports`, {
210
+ method: "POST",
211
+ bearer,
212
+ body: { request: args.request, ...args.receipt !== void 0 ? { receipt: args.receipt } : {} }
213
+ });
214
+ }
215
+ async function getLexExports(apiOrigin, bearer, orgId) {
216
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/lex/exports`, { bearer });
217
+ }
218
+ async function getLexExport(apiOrigin, bearer, orgId, jobId) {
219
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/lex/exports/${encodeURIComponent(jobId)}`, { bearer });
220
+ }
221
+ async function getLexDecision(apiOrigin, bearer, orgId, decisionId) {
222
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/lex/decisions/${encodeURIComponent(decisionId)}`, { bearer });
223
+ }
224
+ async function getLexSubjectDecisions(apiOrigin, bearer, orgId, subject) {
225
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/lex/subjects/${encodeURIComponent(subject)}/decisions`, { bearer });
226
+ }
227
+ async function postLexSubjectErase(apiOrigin, bearer, orgId, subject, receipt) {
228
+ return apiJson(apiOrigin, `/orgs/${encodeURIComponent(orgId)}/lex/subjects/${encodeURIComponent(subject)}/erase`, {
229
+ method: "POST",
230
+ bearer,
231
+ body: { receipt }
232
+ });
233
+ }
234
+ async function getLexExportFile(apiOrigin, bearer, orgId, jobId, path2) {
235
+ const res = await fetch(
236
+ `${apiOrigin.replace(/\/+$/, "")}/orgs/${encodeURIComponent(orgId)}/lex/exports/${encodeURIComponent(jobId)}/files/${path2.split("/").map(encodeURIComponent).join("/")}`,
237
+ { redirect: "error", headers: { Authorization: `Bearer ${bearer}` } }
238
+ );
239
+ if (!res.ok) {
240
+ const body = await res.json().catch(() => null);
241
+ const code = typeof body?.error === "string" ? body.error : `HTTP_${res.status}`;
242
+ throw new SetupApiError(res.status, code, typeof body?.message === "string" ? body.message : code);
243
+ }
244
+ return new Uint8Array(await res.arrayBuffer());
245
+ }
181
246
 
182
247
  // src/app-regions.ts
183
248
  var APP_REGIONS = ["JP", "US", "GB", "EEA"];
@@ -534,6 +599,9 @@ function orgAppRegionsStatement(input2) {
534
599
  regions: input2.regions === null ? null : [...new Set(input2.regions)].sort()
535
600
  };
536
601
  }
602
+ function orgLexSubjectEraseStatement(input2) {
603
+ return { type: "org.lex.subject_erase@1", org: input2.org.trim(), subject: input2.subject.trim() };
604
+ }
537
605
  function orgCardIncorporationStatement(input2) {
538
606
  return {
539
607
  type: "org.card.incorporation_set@1",
@@ -1096,8 +1164,35 @@ async function buildSetupStatus(args) {
1096
1164
  }
1097
1165
 
1098
1166
  // src/setup-client.ts
1099
- async function requireSession(client) {
1100
- const stored = await loadSession(client.sessionPath);
1167
+ var LEX_SUBJECT = /^[A-Za-z0-9._:-]{1,128}$/;
1168
+ var LEX_DECISION_ID = /^[A-Za-z0-9._:-]{1,128}$/;
1169
+ var LEX_EXPORT_PATH = /^(manifest\.json|anchor\.json|items\/\d{5}\.jsonl|decisions\/[A-Za-z0-9._:-]{1,128}\.json)$/;
1170
+ async function bytesDigest(bytes) {
1171
+ return `sha256:${bytesToBase64Url(new Uint8Array(await crypto.subtle.digest("SHA-256", new Uint8Array(bytes))))}`;
1172
+ }
1173
+ function lexRefusal(e) {
1174
+ if (!(e instanceof SetupApiError)) return null;
1175
+ switch (e.code) {
1176
+ case "PROFILE_INVALID":
1177
+ return { ok: false, error: "profile_invalid \u2014 the agreement profile is incomplete (version, service_name, purposes, destinations and terminal_categories are required)." };
1178
+ case "DOCUMENT_NOT_SNAPSHOTTED":
1179
+ return { ok: false, error: "document_not_snapshotted \u2014 run app-lex-document for each document in the profile first, and use the sha256 it returns." };
1180
+ case "EXPORT_RUNNING":
1181
+ return { ok: false, error: "export_running \u2014 another export of this organisation is running. Wait for it, then start again." };
1182
+ case "EXPORT_TOO_LARGE":
1183
+ return { ok: false, error: "export_too_large \u2014 more decisions match than one export holds. Narrow the period (query.from, query.to) and start again." };
1184
+ case "FORBIDDEN":
1185
+ return { ok: false, error: "forbidden \u2014 only an owner or admin of the Org can do this." };
1186
+ case "NOT_FOUND":
1187
+ return { ok: false, error: "not_found \u2014 the Org, the App, the export or the decision was not found, or this is not open to the Org yet." };
1188
+ case "ORG_HOLD":
1189
+ return { ok: false, error: "org_hold \u2014 these records are preserved under a hold, so erasure waits until the hold ends. Nothing was erased." };
1190
+ default:
1191
+ return null;
1192
+ }
1193
+ }
1194
+ async function requireSession(sessionPath) {
1195
+ const stored = await loadSession(sessionPath);
1101
1196
  if (!stored?.session?.accessToken) {
1102
1197
  return {
1103
1198
  ok: false,
@@ -1108,7 +1203,7 @@ async function requireSession(client) {
1108
1203
  }
1109
1204
  };
1110
1205
  }
1111
- return { ok: true, data: { session: stored.session, origins: stored.origins ?? client.origins } };
1206
+ return { ok: true, data: { session: stored.session, origins: stored.origins } };
1112
1207
  }
1113
1208
  async function runPasskeyCeremony(args) {
1114
1209
  const returnTo = setupCeremonyReturnTo(args.origins.developersOrigin);
@@ -1186,7 +1281,7 @@ function createSetupClient(options = {}) {
1186
1281
  const checked = checkOrgCreationTerms(terms);
1187
1282
  if (!checked.ok) return checked;
1188
1283
  const { incorporation } = checked;
1189
- const auth = await requireSession({ origins, sessionPath });
1284
+ const auth = await requireSession(sessionPath);
1190
1285
  if (!auth.ok) return auth;
1191
1286
  const apiOrigin = auth.data.origins.apiOrigin;
1192
1287
  const closed = await getClosedIncorporations(apiOrigin).catch(() => []);
@@ -1240,7 +1335,7 @@ function createSetupClient(options = {}) {
1240
1335
  };
1241
1336
  },
1242
1337
  async orgAnchorFinish(args) {
1243
- const auth = await requireSession({ origins, sessionPath });
1338
+ const auth = await requireSession(sessionPath);
1244
1339
  if (!auth.ok) return auth;
1245
1340
  const payload = await pollCeremonyResult({
1246
1341
  apiOrigin: auth.data.origins.apiOrigin,
@@ -1278,7 +1373,7 @@ function createSetupClient(options = {}) {
1278
1373
  const checked = checkOrgCreationTerms(args);
1279
1374
  if (!checked.ok) return checked;
1280
1375
  const { incorporation } = checked;
1281
- const auth = await requireSession({ origins, sessionPath });
1376
+ const auth = await requireSession(sessionPath);
1282
1377
  if (!auth.ok) return auth;
1283
1378
  try {
1284
1379
  const out = await postVerifyAnchor(auth.data.origins.apiOrigin, auth.data.session.accessToken, {
@@ -1303,7 +1398,7 @@ function createSetupClient(options = {}) {
1303
1398
  }
1304
1399
  },
1305
1400
  async policyBootstrap(orgId) {
1306
- const auth = await requireSession({ origins, sessionPath });
1401
+ const auth = await requireSession(sessionPath);
1307
1402
  if (!auth.ok) return auth;
1308
1403
  const detail = await getOrg(auth.data.origins.apiOrigin, auth.data.session.accessToken, orgId);
1309
1404
  try {
@@ -1335,7 +1430,7 @@ function createSetupClient(options = {}) {
1335
1430
  const checked = checkOrgCreationTerms(args, INCORPORATION_TERMS_HUMAN);
1336
1431
  if (!checked.ok) return checked;
1337
1432
  const code = checked.incorporation;
1338
- const auth = await requireSession({ origins, sessionPath });
1433
+ const auth = await requireSession(sessionPath);
1339
1434
  if (!auth.ok) return auth;
1340
1435
  const sub = auth.data.session.sub;
1341
1436
  if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
@@ -1373,7 +1468,7 @@ function createSetupClient(options = {}) {
1373
1468
  async cardCheckout(orgId, opts = {}) {
1374
1469
  const offer = opts.offer === "bundle" ? "bundle" : "meter";
1375
1470
  const lang = checkoutLang(opts.lang);
1376
- const auth = await requireSession({ origins, sessionPath });
1471
+ const auth = await requireSession(sessionPath);
1377
1472
  if (!auth.ok) return auth;
1378
1473
  const sub = auth.data.session.sub;
1379
1474
  if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
@@ -1456,7 +1551,7 @@ function createSetupClient(options = {}) {
1456
1551
  };
1457
1552
  },
1458
1553
  async appRegister(args) {
1459
- const auth = await requireSession({ origins, sessionPath });
1554
+ const auth = await requireSession(sessionPath);
1460
1555
  if (!auth.ok) return auth;
1461
1556
  const sub = auth.data.session.sub;
1462
1557
  if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
@@ -1501,7 +1596,7 @@ function createSetupClient(options = {}) {
1501
1596
  };
1502
1597
  },
1503
1598
  async appHostPlan(orgId, appId) {
1504
- const auth = await requireSession({ origins, sessionPath });
1599
+ const auth = await requireSession(sessionPath);
1505
1600
  if (!auth.ok) return auth;
1506
1601
  const ch = await getHostChallenge(auth.data.origins.apiOrigin, auth.data.session.accessToken, orgId, appId);
1507
1602
  return {
@@ -1518,7 +1613,7 @@ function createSetupClient(options = {}) {
1518
1613
  };
1519
1614
  },
1520
1615
  async appVerifyHost(args) {
1521
- const auth = await requireSession({ origins, sessionPath });
1616
+ const auth = await requireSession(sessionPath);
1522
1617
  if (!auth.ok) return auth;
1523
1618
  const ch = await getHostChallenge(
1524
1619
  auth.data.origins.apiOrigin,
@@ -1559,7 +1654,7 @@ function createSetupClient(options = {}) {
1559
1654
  }
1560
1655
  },
1561
1656
  async declarationSet(args) {
1562
- const auth = await requireSession({ origins, sessionPath });
1657
+ const auth = await requireSession(sessionPath);
1563
1658
  if (!auth.ok) return auth;
1564
1659
  const declaration = { endUsers: args.endUsers, uses: args.uses };
1565
1660
  const cer = await runPasskeyCeremony({
@@ -1583,7 +1678,7 @@ function createSetupClient(options = {}) {
1583
1678
  const read = readAppRegionsInput(args.regions);
1584
1679
  if (!read.ok) return read;
1585
1680
  const regions = read.regions;
1586
- const auth = await requireSession({ origins, sessionPath });
1681
+ const auth = await requireSession(sessionPath);
1587
1682
  if (!auth.ok) return auth;
1588
1683
  const sub = auth.data.session.sub;
1589
1684
  if (!sub) return { ok: false, error: "session_missing_sub \u2014 re-login" };
@@ -1616,6 +1711,197 @@ function createSetupClient(options = {}) {
1616
1711
  throw e;
1617
1712
  }
1618
1713
  },
1714
+ async appLexDocument(args) {
1715
+ const auth = await requireSession(sessionPath);
1716
+ if (!auth.ok) return auth;
1717
+ try {
1718
+ return { ok: true, data: await postAppLexDocument(auth.data.origins.apiOrigin, auth.data.session.accessToken, args.orgId, args.appId, args.url) };
1719
+ } catch (e) {
1720
+ const refusal = lexRefusal(e);
1721
+ if (refusal) return refusal;
1722
+ throw e;
1723
+ }
1724
+ },
1725
+ async appLexProfileSet(args) {
1726
+ const auth = await requireSession(sessionPath);
1727
+ if (!auth.ok) return auth;
1728
+ const apiOrigin = auth.data.origins.apiOrigin;
1729
+ const bearer = auth.data.session.accessToken;
1730
+ try {
1731
+ const prepared = await postAppLexProfileStatement(apiOrigin, bearer, args.orgId, args.appId, args.profile);
1732
+ const cer = await runPasskeyCeremony({
1733
+ origins: auth.data.origins,
1734
+ bearer,
1735
+ statement: prepared.statement,
1736
+ displayHint: args.profile === null ? "Clear the App's agreement profile" : "Set the App's agreement profile",
1737
+ openBrowserFlag
1738
+ });
1739
+ const proof = await cer.wait();
1740
+ return { ok: true, data: await putAppLexProfile(apiOrigin, bearer, args.orgId, args.appId, { profile: args.profile, receipt: proof }) };
1741
+ } catch (e) {
1742
+ const refusal = lexRefusal(e);
1743
+ if (refusal) return refusal;
1744
+ throw e;
1745
+ }
1746
+ },
1747
+ async lexCounts(args) {
1748
+ const auth = await requireSession(sessionPath);
1749
+ if (!auth.ok) return auth;
1750
+ try {
1751
+ return { ok: true, data: await postLexDecisionCounts(auth.data.origins.apiOrigin, auth.data.session.accessToken, args.orgId, args.query ?? {}) };
1752
+ } catch (e) {
1753
+ const refusal = lexRefusal(e);
1754
+ if (refusal) return refusal;
1755
+ throw e;
1756
+ }
1757
+ },
1758
+ async lexExport(args) {
1759
+ const auth = await requireSession(sessionPath);
1760
+ if (!auth.ok) return auth;
1761
+ const apiOrigin = auth.data.origins.apiOrigin;
1762
+ const bearer = auth.data.session.accessToken;
1763
+ try {
1764
+ const prepared = await postLexExportStatement(apiOrigin, bearer, args.orgId, args.request);
1765
+ let receipt;
1766
+ if (prepared.statement) {
1767
+ const cer = await runPasskeyCeremony({
1768
+ origins: auth.data.origins,
1769
+ bearer,
1770
+ statement: prepared.statement,
1771
+ displayHint: "Export the organisation's agreement records",
1772
+ openBrowserFlag
1773
+ });
1774
+ receipt = await cer.wait();
1775
+ }
1776
+ return { ok: true, data: await postLexExport(apiOrigin, bearer, args.orgId, { request: args.request, ...receipt ? { receipt } : {} }) };
1777
+ } catch (e) {
1778
+ const refusal = lexRefusal(e);
1779
+ if (refusal) return refusal;
1780
+ throw e;
1781
+ }
1782
+ },
1783
+ async lexExports(args) {
1784
+ const auth = await requireSession(sessionPath);
1785
+ if (!auth.ok) return auth;
1786
+ try {
1787
+ return { ok: true, data: await getLexExports(auth.data.origins.apiOrigin, auth.data.session.accessToken, args.orgId) };
1788
+ } catch (e) {
1789
+ const refusal = lexRefusal(e);
1790
+ if (refusal) return refusal;
1791
+ throw e;
1792
+ }
1793
+ },
1794
+ async lexExportStatus(args) {
1795
+ const auth = await requireSession(sessionPath);
1796
+ if (!auth.ok) return auth;
1797
+ try {
1798
+ return { ok: true, data: await getLexExport(auth.data.origins.apiOrigin, auth.data.session.accessToken, args.orgId, args.jobId) };
1799
+ } catch (e) {
1800
+ const refusal = lexRefusal(e);
1801
+ if (refusal) return refusal;
1802
+ throw e;
1803
+ }
1804
+ },
1805
+ async lexExportDownload(args) {
1806
+ if (!/^[0-9a-f]{32}$/.test(args.jobId)) return { ok: false, error: "job_id_invalid" };
1807
+ const auth = await requireSession(sessionPath);
1808
+ if (!auth.ok) return auth;
1809
+ const apiOrigin = auth.data.origins.apiOrigin;
1810
+ const bearer = auth.data.session.accessToken;
1811
+ try {
1812
+ const { job } = await getLexExport(apiOrigin, bearer, args.orgId, args.jobId);
1813
+ if (job.state !== "done" || typeof job.manifest_digest !== "string") {
1814
+ return { ok: false, error: `export_not_done \u2014 the export is ${String(job.state)}. Check again with lex-export-status.` };
1815
+ }
1816
+ const manifestBytes = await getLexExportFile(apiOrigin, bearer, args.orgId, args.jobId, "manifest.json");
1817
+ if (await bytesDigest(manifestBytes) !== job.manifest_digest) {
1818
+ return { ok: false, error: "export_manifest_mismatch \u2014 the manifest does not hash to the digest Clavis anchored. Nothing was kept." };
1819
+ }
1820
+ const manifest = JSON.parse(new TextDecoder().decode(manifestBytes));
1821
+ if (manifest?.kind !== "lex.package@1" || manifest.job_id !== args.jobId || !Array.isArray(manifest.files)) {
1822
+ return { ok: false, error: "invalid_export_manifest" };
1823
+ }
1824
+ const files = [];
1825
+ const seen = /* @__PURE__ */ new Set(["manifest.json", "anchor.json"]);
1826
+ await mkdir(args.dir, { recursive: true, mode: 448 });
1827
+ const staging = await mkdtemp(join(args.dir, ".clavis-export-"));
1828
+ const store = async (path2, bytes) => {
1829
+ await mkdir(dirname(join(staging, path2)), { recursive: true, mode: 448 });
1830
+ await writeFile(join(staging, path2), bytes, { flag: "wx", mode: 384 });
1831
+ files.push({ path: path2, bytes: bytes.byteLength });
1832
+ };
1833
+ try {
1834
+ await store("manifest.json", manifestBytes);
1835
+ for (const entry of manifest.files) {
1836
+ if (typeof entry?.path !== "string" || !LEX_EXPORT_PATH.test(entry.path) || seen.has(entry.path)) {
1837
+ return { ok: false, error: "invalid_export_manifest" };
1838
+ }
1839
+ seen.add(entry.path);
1840
+ const bytes = await getLexExportFile(apiOrigin, bearer, args.orgId, args.jobId, entry.path);
1841
+ if (bytes.byteLength !== entry.bytes || await bytesDigest(bytes) !== entry.sha256) {
1842
+ return { ok: false, error: `export_file_mismatch \u2014 ${entry.path} differs from the manifest.` };
1843
+ }
1844
+ await store(entry.path, bytes);
1845
+ }
1846
+ await store("anchor.json", await getLexExportFile(apiOrigin, bearer, args.orgId, args.jobId, "anchor.json"));
1847
+ const root = join(args.dir, args.jobId);
1848
+ await rename(staging, root);
1849
+ return { ok: true, data: { dir: root, manifest_digest: job.manifest_digest, files } };
1850
+ } finally {
1851
+ await rm(staging, { recursive: true, force: true });
1852
+ }
1853
+ } catch (e) {
1854
+ const refusal = lexRefusal(e);
1855
+ if (refusal) return refusal;
1856
+ throw e;
1857
+ }
1858
+ },
1859
+ async lexDecision(args) {
1860
+ if (!LEX_DECISION_ID.test(args.decisionId)) return { ok: false, error: "decision_id_invalid \u2014 pass the decision_id Clavis returned for the agreement." };
1861
+ const auth = await requireSession(sessionPath);
1862
+ if (!auth.ok) return auth;
1863
+ try {
1864
+ return { ok: true, data: await getLexDecision(auth.data.origins.apiOrigin, auth.data.session.accessToken, args.orgId, args.decisionId) };
1865
+ } catch (e) {
1866
+ const refusal = lexRefusal(e);
1867
+ if (refusal) return refusal;
1868
+ throw e;
1869
+ }
1870
+ },
1871
+ async lexSubjectDecisions(args) {
1872
+ if (!LEX_SUBJECT.test(args.subject)) return { ok: false, error: "subject_invalid \u2014 pass the person's ID in your App (the sub you passed as allowedSub)." };
1873
+ const auth = await requireSession(sessionPath);
1874
+ if (!auth.ok) return auth;
1875
+ try {
1876
+ return { ok: true, data: await getLexSubjectDecisions(auth.data.origins.apiOrigin, auth.data.session.accessToken, args.orgId, args.subject) };
1877
+ } catch (e) {
1878
+ const refusal = lexRefusal(e);
1879
+ if (refusal) return refusal;
1880
+ throw e;
1881
+ }
1882
+ },
1883
+ async lexSubjectErase(args) {
1884
+ if (!LEX_SUBJECT.test(args.subject)) return { ok: false, error: "subject_invalid \u2014 pass the person's ID in your App (the sub you passed as allowedSub)." };
1885
+ const auth = await requireSession(sessionPath);
1886
+ if (!auth.ok) return auth;
1887
+ const apiOrigin = auth.data.origins.apiOrigin;
1888
+ const bearer = auth.data.session.accessToken;
1889
+ try {
1890
+ const cer = await runPasskeyCeremony({
1891
+ origins: auth.data.origins,
1892
+ bearer,
1893
+ statement: orgLexSubjectEraseStatement({ org: args.orgId, subject: args.subject }),
1894
+ displayHint: "Erase one person's agreement records",
1895
+ openBrowserFlag
1896
+ });
1897
+ const proof = await cer.wait();
1898
+ return { ok: true, data: await postLexSubjectErase(apiOrigin, bearer, args.orgId, args.subject, proof) };
1899
+ } catch (e) {
1900
+ const refusal = lexRefusal(e);
1901
+ if (refusal) return refusal;
1902
+ throw e;
1903
+ }
1904
+ },
1619
1905
  async emitEnv(args) {
1620
1906
  const jwk = args.operatePrivateJwkJson?.trim() || await readOperatePrivateJwk(args.appId) || "";
1621
1907
  if (!jwk) {