@agent-native/dispatch 0.42.5-nightly-20261111212500 → 0.42.5

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 (37) hide show
  1. package/CHANGELOG.md +8 -46
  2. package/dist/actions/create-vault-secret.js +2 -2
  3. package/dist/actions/create-vault-secret.js.map +1 -1
  4. package/dist/actions/index.d.ts.map +1 -1
  5. package/dist/actions/index.js +0 -2
  6. package/dist/actions/index.js.map +1 -1
  7. package/dist/actions/list-vault-secrets.d.ts +1 -1
  8. package/dist/actions/list-vault-secrets.js +3 -4
  9. package/dist/actions/list-vault-secrets.js.map +1 -1
  10. package/dist/actions/provider-api-register.d.ts +12 -12
  11. package/dist/actions/update-vault-secret.js +2 -2
  12. package/dist/actions/update-vault-secret.js.map +1 -1
  13. package/dist/components/app-keys-popover.d.ts.map +1 -1
  14. package/dist/components/app-keys-popover.js +8 -19
  15. package/dist/components/app-keys-popover.js.map +1 -1
  16. package/dist/routes/pages/vault.d.ts.map +1 -1
  17. package/dist/routes/pages/vault.js +3 -9
  18. package/dist/routes/pages/vault.js.map +1 -1
  19. package/dist/server/lib/vault-store.d.ts +18 -68
  20. package/dist/server/lib/vault-store.d.ts.map +1 -1
  21. package/dist/server/lib/vault-store.js +98 -273
  22. package/dist/server/lib/vault-store.js.map +1 -1
  23. package/package.json +4 -4
  24. package/src/actions/create-vault-secret.ts +2 -2
  25. package/src/actions/index.spec.ts +1 -1
  26. package/src/actions/index.ts +0 -2
  27. package/src/actions/list-vault-secrets.ts +3 -4
  28. package/src/actions/update-vault-secret.ts +3 -2
  29. package/src/components/app-keys-popover.tsx +1 -39
  30. package/src/routes/pages/vault.tsx +21 -31
  31. package/src/server/lib/vault-store.spec.ts +377 -450
  32. package/src/server/lib/vault-store.ts +141 -340
  33. package/dist/actions/sync-vault-to-app.d.ts +0 -32
  34. package/dist/actions/sync-vault-to-app.d.ts.map +0 -1
  35. package/dist/actions/sync-vault-to-app.js +0 -13
  36. package/dist/actions/sync-vault-to-app.js.map +0 -1
  37. package/src/actions/sync-vault-to-app.ts +0 -15
@@ -4,8 +4,8 @@ import { and, desc, eq, isNull, or, sql } from "@agent-native/core/db/schema";
4
4
  import { ssrfSafeFetch } from "@agent-native/core/extensions/url-safety";
5
5
  import {
6
6
  deleteAppSecret,
7
- last4,
8
7
  listAppSecretsForScope,
8
+ readAppSecret,
9
9
  VAULT_SYNC_DESCRIPTION_PREFIX,
10
10
  writeAppSecret,
11
11
  type SecretScope,
@@ -18,7 +18,6 @@ import {
18
18
  putOrgSetting,
19
19
  putUserSetting,
20
20
  } from "@agent-native/core/settings";
21
- import { asc, gt } from "drizzle-orm";
22
21
 
23
22
  import { getDb, schema } from "../../db/index.js";
24
23
  import {
@@ -29,6 +28,13 @@ import {
29
28
 
30
29
  const VAULT_ACCESS_SETTINGS_KEY = "dispatch-vault-access-settings";
31
30
 
31
+ /**
32
+ * `vault_secrets.value` is NOT NULL and migrations can't drop columns, so it
33
+ * stays as an always-empty column; the value lives only, encrypted, in
34
+ * `app_secrets`. Treat "" as "no plaintext here", never as "no secret".
35
+ */
36
+ const SEALED_VAULT_VALUE = "";
37
+
32
38
  export type VaultAccessMode = "all-apps" | "manual";
33
39
 
34
40
  export interface VaultAccessSettings {
@@ -101,44 +107,6 @@ function safeJson(value: unknown) {
101
107
  return JSON.stringify(value ?? null);
102
108
  }
103
109
 
104
- function workspaceBaseOrigins(): Set<string> {
105
- const out = new Set<string>();
106
- for (const value of [
107
- process.env.WORKSPACE_GATEWAY_URL,
108
- process.env.APP_URL,
109
- process.env.URL,
110
- process.env.DEPLOY_URL,
111
- process.env.BETTER_AUTH_URL,
112
- ]) {
113
- if (!value) continue;
114
- try {
115
- out.add(new URL(value).origin);
116
- } catch {
117
- // Ignore malformed deploy metadata.
118
- }
119
- }
120
- return out;
121
- }
122
-
123
- export function isTrustedEnvVarSyncAgentUrl(agentUrl: string): boolean {
124
- let parsed: URL;
125
- try {
126
- parsed = new URL(agentUrl);
127
- } catch {
128
- return false;
129
- }
130
- const hostname = parsed.hostname.toLowerCase();
131
- if (
132
- hostname === "localhost" ||
133
- hostname === "127.0.0.1" ||
134
- hostname === "::1" ||
135
- hostname.endsWith(".localhost")
136
- ) {
137
- return true;
138
- }
139
- return workspaceBaseOrigins().has(parsed.origin);
140
- }
141
-
142
110
  function scopedFilter<T extends { ownerEmail: any; orgId: any }>(table: T) {
143
111
  return ctxScope(table, requireVaultCtx());
144
112
  }
@@ -306,8 +274,8 @@ export async function createSecret(
306
274
  credentialKey: string;
307
275
  value: string;
308
276
  name: string;
309
- provider?: string | null;
310
- description?: string | null;
277
+ provider?: string | null | undefined;
278
+ description?: string | null | undefined;
311
279
  },
312
280
  ctx: VaultCtx = requireVaultCtx(),
313
281
  ) {
@@ -316,6 +284,7 @@ export async function createSecret(
316
284
  const timestamp = now();
317
285
  const credentialKey = normalizeCredentialKey(input.credentialKey);
318
286
  if (!credentialKey) throw new Error("Credential key is required");
287
+ if (!input.value) throw new Error("Secret value is required");
319
288
  const existing = await db
320
289
  .select()
321
290
  .from(schema.vaultSecrets)
@@ -329,26 +298,32 @@ export async function createSecret(
329
298
  .limit(1);
330
299
 
331
300
  if (existing[0]) {
301
+ const found = existing[0];
332
302
  await db
333
303
  .update(schema.vaultSecrets)
334
304
  .set({
335
305
  name: input.name,
336
306
  credentialKey,
337
- value: input.value,
307
+ value: SEALED_VAULT_VALUE,
338
308
  provider: input.provider || null,
339
309
  description: input.description || null,
340
310
  updatedAt: timestamp,
341
311
  })
342
312
  .where(
343
313
  and(
344
- eq(schema.vaultSecrets.id, existing[0].id),
314
+ eq(schema.vaultSecrets.id, found.id),
345
315
  ctxScope(schema.vaultSecrets, ctx),
346
316
  ),
347
317
  );
318
+ await storeSecretValue(
319
+ ctxForSecretRow(found, ctx),
320
+ { credentialKey, name: input.name },
321
+ input.value,
322
+ );
348
323
 
349
324
  await recordVaultAudit({
350
325
  action: "secret.updated",
351
- secretId: existing[0].id,
326
+ secretId: found.id,
352
327
  summary: `Updated secret "${input.name}" (${credentialKey})`,
353
328
  metadata: { credentialKey, provider: input.provider },
354
329
  });
@@ -356,18 +331,11 @@ export async function createSecret(
356
331
  await recordAudit({
357
332
  action: "vault.secret.updated",
358
333
  targetType: "vault-secret",
359
- targetId: existing[0].id,
334
+ targetId: found.id,
360
335
  summary: `Updated vault secret "${input.name}" (${credentialKey})`,
361
336
  });
362
337
 
363
- const updated = await getSecret(existing[0].id, ctx);
364
- if (updated) {
365
- await syncSecretsToCredentialStore(
366
- [updated],
367
- ctxForSecretRow(updated, ctx),
368
- );
369
- }
370
- return updated;
338
+ return getSecret(found.id, ctx);
371
339
  }
372
340
 
373
341
  const secretId = id();
@@ -379,13 +347,14 @@ export async function createSecret(
379
347
  orgId: ctx.orgId,
380
348
  name: input.name,
381
349
  credentialKey,
382
- value: input.value,
350
+ value: SEALED_VAULT_VALUE,
383
351
  provider: input.provider || null,
384
352
  description: input.description || null,
385
353
  createdBy: actor,
386
354
  createdAt: timestamp,
387
355
  updatedAt: timestamp,
388
356
  });
357
+ await storeSecretValue(ctx, { credentialKey, name: input.name }, input.value);
389
358
 
390
359
  await recordVaultAudit({
391
360
  action: "secret.created",
@@ -401,14 +370,7 @@ export async function createSecret(
401
370
  summary: `Created vault secret "${input.name}" (${credentialKey})`,
402
371
  });
403
372
 
404
- const created = await getSecret(secretId, ctx);
405
- if (created) {
406
- await syncSecretsToCredentialStore(
407
- [created],
408
- ctxForSecretRow(created, ctx),
409
- );
410
- }
411
- return created;
373
+ return getSecret(secretId, ctx);
412
374
  }
413
375
 
414
376
  export async function updateSecret(
@@ -416,11 +378,11 @@ export async function updateSecret(
416
378
  input:
417
379
  | string
418
380
  | {
419
- credentialKey?: string;
420
- value?: string;
421
- name?: string;
422
- provider?: string | null;
423
- description?: string | null;
381
+ credentialKey?: string | undefined;
382
+ value?: string | undefined;
383
+ name?: string | undefined;
384
+ provider?: string | null | undefined;
385
+ description?: string | null | undefined;
424
386
  },
425
387
  ctx: VaultCtx = requireVaultCtx(),
426
388
  ) {
@@ -436,8 +398,9 @@ export async function updateSecret(
436
398
  if (!credentialKey) throw new Error("Credential key is required");
437
399
  const name = patch.name !== undefined ? patch.name.trim() : existing.name;
438
400
  if (!name) throw new Error("Secret name is required");
439
- const value = patch.value !== undefined ? patch.value : existing.value;
440
- if (!value) throw new Error("Secret value is required");
401
+ if (patch.value !== undefined && !patch.value) {
402
+ throw new Error("Secret value is required");
403
+ }
441
404
  const provider =
442
405
  patch.provider !== undefined ? patch.provider || null : existing.provider;
443
406
  const description =
@@ -461,12 +424,27 @@ export async function updateSecret(
461
424
  }
462
425
  }
463
426
 
427
+ const storeCtx = ctxForSecretRow(existing, ctx);
428
+ let valueForKey = patch.value;
429
+ if (!valueForKey && credentialKey !== existing.credentialKey) {
430
+ // A rename carries the stored value to the new key. A failed read throws;
431
+ // only a missing copy means there is nothing to move.
432
+ const current = await readAppSecret({
433
+ key: existing.credentialKey,
434
+ ...credentialStoreScopeForVaultCtx(storeCtx),
435
+ });
436
+ valueForKey = current?.value;
437
+ }
438
+
464
439
  await db
465
440
  .update(schema.vaultSecrets)
466
441
  .set({
467
442
  name,
468
443
  credentialKey,
469
- value,
444
+ // Only a new value empties the row. A row that still holds an older
445
+ // plaintext value keeps it until it is cleared in bulk, so a label edit
446
+ // can never write that stale value over a newer one in the credential store.
447
+ ...(patch.value !== undefined ? { value: SEALED_VAULT_VALUE } : {}),
470
448
  provider,
471
449
  description,
472
450
  updatedAt: now(),
@@ -477,6 +455,9 @@ export async function updateSecret(
477
455
  ctxScope(schema.vaultSecrets, ctx),
478
456
  ),
479
457
  );
458
+ if (valueForKey) {
459
+ await storeSecretValue(storeCtx, { credentialKey, name }, valueForKey);
460
+ }
480
461
 
481
462
  const auditMetadata = {
482
463
  name,
@@ -492,7 +473,7 @@ export async function updateSecret(
492
473
  description,
493
474
  previousDescription:
494
475
  description !== existing.description ? existing.description : undefined,
495
- valueChanged: value !== existing.value ? true : undefined,
476
+ valueChanged: patch.value !== undefined ? true : undefined,
496
477
  };
497
478
 
498
479
  await recordVaultAudit({
@@ -511,12 +492,6 @@ export async function updateSecret(
511
492
  });
512
493
 
513
494
  const updated = await getSecret(secretId, ctx);
514
- if (updated) {
515
- await syncSecretsToCredentialStore(
516
- [updated],
517
- ctxForSecretRow(updated, ctx),
518
- );
519
- }
520
495
  if (updated && credentialKey !== existing.credentialKey) {
521
496
  await cleanupSyncedCredentialKeysIfUnused(ctxForRow(existing), [
522
497
  existing.credentialKey,
@@ -787,11 +762,18 @@ export async function revokeGrant(
787
762
 
788
763
  type VaultSecretRow = typeof schema.vaultSecrets.$inferSelect;
789
764
 
765
+ /**
766
+ * What the credential store holds for a vault row: a readable value, nothing,
767
+ * or a value this deployment cannot decrypt (a rotated key, a copied database).
768
+ */
769
+ export type VaultValueStatus = "stored" | "missing" | "unreadable";
770
+
790
771
  export interface VaultSecretMetadata {
791
772
  id: string;
792
773
  name: string;
793
774
  credentialKey: string;
794
775
  last4: string;
776
+ valueStatus: VaultValueStatus;
795
777
  provider: string | null;
796
778
  description: string | null;
797
779
  createdBy: string;
@@ -799,15 +781,17 @@ export interface VaultSecretMetadata {
799
781
  updatedAt: number;
800
782
  }
801
783
 
802
- export function toVaultSecretMetadata(
803
- secret: VaultSecretRow | null,
804
- ): VaultSecretMetadata | null {
805
- if (!secret) return null;
784
+ function vaultSecretMetadata(
785
+ secret: VaultSecretRow,
786
+ last4Value: string,
787
+ valueStatus: VaultValueStatus,
788
+ ): VaultSecretMetadata {
806
789
  return {
807
790
  id: secret.id,
808
791
  name: secret.name,
809
792
  credentialKey: secret.credentialKey,
810
- last4: last4(secret.value),
793
+ last4: last4Value,
794
+ valueStatus,
811
795
  provider: secret.provider,
812
796
  description: secret.description,
813
797
  createdBy: secret.createdBy,
@@ -824,136 +808,90 @@ export function credentialStoreScopeForVaultCtx(ctx: VaultCtx): {
824
808
  return { scope: "workspace", scopeId: `solo:${ctx.ownerEmail}` };
825
809
  }
826
810
 
827
- export async function syncSecretsToCredentialStore(
828
- secrets: VaultSecretRow[],
829
- ctx: VaultCtx,
830
- ) {
831
- const target = credentialStoreScopeForVaultCtx(ctx);
832
- const syncedKeys: string[] = [];
833
-
834
- for (const secret of secrets) {
835
- if (!secret.credentialKey || !secret.value) continue;
836
- await writeAppSecret({
837
- key: secret.credentialKey,
838
- value: secret.value,
839
- scope: target.scope,
840
- scopeId: target.scopeId,
841
- description: `${VAULT_SYNC_DESCRIPTION_PREFIX} ${secret.name}`,
842
- });
843
- syncedKeys.push(secret.credentialKey);
844
- }
845
-
846
- return { ...target, keys: syncedKeys };
847
- }
848
-
849
811
  /**
850
- * Group secrets by the tenant their credential-store rows must land in.
851
- *
852
- * Every sync path must write a secret under the org that *owns the row*, not
853
- * under whoever happens to be syncing: `writeAppSecret` upserts, so syncing
854
- * with the caller's ctx copies credential material into the caller's org
855
- * instead of moving it, and it accumulates there permanently.
812
+ * Masked metadata for a page of vault rows. The preview is read from the
813
+ * encrypted copy in the credential store, one read per store scope, because
814
+ * the vault row itself holds no value.
856
815
  */
857
- function groupSecretsByTenant(
816
+ export async function listVaultSecretMetadata(
858
817
  rows: VaultSecretRow[],
859
- resolveCtx: (row: VaultSecretRow) => VaultCtx,
860
- ): { ctx: VaultCtx; rows: VaultSecretRow[] }[] {
861
- const groups = new Map<string, { ctx: VaultCtx; rows: VaultSecretRow[] }>();
818
+ fallback: VaultCtx = requireVaultCtx(),
819
+ ): Promise<VaultSecretMetadata[]> {
820
+ const storeKey = (row: VaultSecretRow) => {
821
+ const target = credentialStoreScopeForVaultCtx(
822
+ ctxForSecretRow(row, fallback),
823
+ );
824
+ return { target, scopeKey: `${target.scope}\u0000${target.scopeId}` };
825
+ };
826
+ const scopes = new Map<string, ReturnType<typeof storeKey>["target"]>();
862
827
  for (const row of rows) {
863
- if (!row.credentialKey || !row.value) continue;
864
- const ctx = resolveCtx(row);
865
- const groupKey = `${ctx.orgId ?? ""}\u0000${ctx.ownerEmail}`;
866
- const group = groups.get(groupKey);
867
- if (group) {
868
- group.rows.push(row);
869
- } else {
870
- groups.set(groupKey, { ctx, rows: [row] });
828
+ const { target, scopeKey } = storeKey(row);
829
+ scopes.set(scopeKey, target);
830
+ }
831
+ const previews = new Map<string, string>();
832
+ for (const [scopeKey, target] of scopes) {
833
+ for (const meta of await listAppSecretsForScope(
834
+ target.scope,
835
+ target.scopeId,
836
+ )) {
837
+ previews.set(`${scopeKey}\u0000${meta.key}`, meta.last4);
871
838
  }
872
839
  }
873
- return [...groups.values()];
840
+ return rows.map((row) => {
841
+ const preview = previews.get(
842
+ `${storeKey(row).scopeKey}\u0000${row.credentialKey}`,
843
+ );
844
+ // The scope listing reports a copy it cannot decrypt as an empty preview,
845
+ // and a stored value is never empty, so empty here means unreadable.
846
+ if (preview === undefined) return vaultSecretMetadata(row, "", "missing");
847
+ return vaultSecretMetadata(
848
+ row,
849
+ preview,
850
+ preview === "" ? "unreadable" : "stored",
851
+ );
852
+ });
874
853
  }
875
854
 
876
- /**
877
- * Re-sync one bounded page of vault secrets across tenants into the shared
878
- * credential store. Continue with `nextCursor` only from an explicit
879
- * maintenance caller; this must not run automatically during process startup.
880
- *
881
- * `syncSecretsToCredentialStore` normally only runs on `createSecret` /
882
- * `updateSecret`, so it only re-encrypts the rows a user happens to touch.
883
- * When the shared `app_secrets` encryption format changes underneath it
884
- * (e.g. a new dual-write format, or a change to how key material is
885
- * derived), existing rows are stuck on the old format until someone
886
- * manually re-saves each vault secret. This reads a keyset page directly —
887
- * bypassing the ctx-scoped `listSecrets()` — groups the rows by their
888
- * (orgId, ownerEmail) tenant, and re-runs the sync per group.
889
- *
890
- * A failure syncing one tenant's group is caught and logged (key NAMES
891
- * only, never values) so it can't block the rest of the resync. If a group
892
- * fails, `nextCursor` rewinds to before its first row so the next pass retries
893
- * it; check `failedGroups` before treating a null cursor as completion.
894
- */
895
- export async function resyncVaultSecretsToCredentialStorePage(
896
- options: {
897
- afterId?: string;
898
- limit?: number;
899
- } = {},
900
- ): Promise<{
901
- groups: number;
902
- failedGroups: number;
903
- syncedKeys: number;
904
- nextCursor: string | null;
905
- }> {
906
- const requestedLimit = options.limit ?? 100;
907
- const limit = Number.isFinite(requestedLimit)
908
- ? Math.min(500, Math.max(1, Math.floor(requestedLimit)))
909
- : 100;
910
- const db = getDb();
911
- const rowsWithNext = await db
912
- .select()
913
- .from(schema.vaultSecrets)
914
- .where(
915
- options.afterId ? gt(schema.vaultSecrets.id, options.afterId) : undefined,
916
- )
917
- .orderBy(asc(schema.vaultSecrets.id))
918
- .limit(limit + 1);
919
- const hasMore = rowsWithNext.length > limit;
920
- const rows = hasMore ? rowsWithNext.slice(0, limit) : rowsWithNext;
921
-
922
- const groups = groupSecretsByTenant(rows, ctxForRow);
923
-
924
- let failedGroups = 0;
925
- let syncedKeys = 0;
926
- let firstFailedRowIndex = Number.POSITIVE_INFINITY;
927
-
928
- for (const { ctx, rows: groupRows } of groups) {
929
- try {
930
- const result = await syncSecretsToCredentialStore(groupRows, ctx);
931
- syncedKeys += result.keys.length;
932
- } catch (error) {
933
- failedGroups++;
934
- const firstRowIndex = rows.findIndex(
935
- (row) => row.id === groupRows[0]?.id,
936
- );
937
- firstFailedRowIndex = Math.min(firstFailedRowIndex, firstRowIndex);
938
- const keyNames = groupRows.map((row) => row.credentialKey).join(", ");
939
- console.warn(
940
- `[dispatch] vault boot resync failed for org=${ctx.orgId ?? "(solo)"} owner=${ctx.ownerEmail}; affected keys: ${keyNames}`,
941
- error instanceof Error ? error.message : error,
942
- );
943
- }
855
+ export async function getVaultSecretMetadata(
856
+ row: VaultSecretRow | null,
857
+ fallback: VaultCtx = requireVaultCtx(),
858
+ ): Promise<VaultSecretMetadata | null> {
859
+ if (!row) return null;
860
+ try {
861
+ const copy = await readAppSecret({
862
+ key: row.credentialKey,
863
+ ...credentialStoreScopeForVaultCtx(ctxForSecretRow(row, fallback)),
864
+ });
865
+ return copy
866
+ ? vaultSecretMetadata(row, copy.last4, "stored")
867
+ : vaultSecretMetadata(row, "", "missing");
868
+ } catch (error) {
869
+ if (!isUnreadableSecretError(error)) throw error;
870
+ return vaultSecretMetadata(row, "", "unreadable");
944
871
  }
872
+ }
945
873
 
946
- return {
947
- groups: groups.length,
948
- failedGroups,
949
- syncedKeys,
950
- nextCursor:
951
- failedGroups > 0
952
- ? (rows[firstFailedRowIndex - 1]?.id ?? options.afterId ?? null)
953
- : hasMore
954
- ? (rows.at(-1)?.id ?? null)
955
- : null,
956
- };
874
+ /** Core does not export `AppSecretDecryptionError`; it is recognised by its code. */
875
+ function isUnreadableSecretError(error: unknown): boolean {
876
+ return (
877
+ (error as { errorCode?: unknown }).errorCode === "app_secret_unreadable"
878
+ );
879
+ }
880
+
881
+ /** Encrypt a vault secret's value into the credential store. */
882
+ async function storeSecretValue(
883
+ ctx: VaultCtx,
884
+ secret: { credentialKey: string; name: string },
885
+ value: string,
886
+ ): Promise<void> {
887
+ const target = credentialStoreScopeForVaultCtx(ctx);
888
+ await writeAppSecret({
889
+ key: secret.credentialKey,
890
+ value,
891
+ scope: target.scope,
892
+ scopeId: target.scopeId,
893
+ description: `${VAULT_SYNC_DESCRIPTION_PREFIX} ${secret.name}`,
894
+ });
957
895
  }
958
896
 
959
897
  export async function cleanupSyncedCredentialKeysIfUnused(
@@ -991,143 +929,6 @@ export async function cleanupSyncedCredentialKeysIfUnused(
991
929
  }
992
930
  }
993
931
 
994
- export async function syncGrantsToApp(
995
- appId: string,
996
- ctx: VaultCtx = requireVaultCtx(),
997
- ) {
998
- await assertCanManageVault();
999
- const db = getDb();
1000
- const access = await getVaultAccessSettings();
1001
- const agents = await discoverAgents("dispatch");
1002
- const agent = agents.find((a) => a.id === appId);
1003
- if (!agent) throw new Error(`App "${appId}" not found in agent registry`);
1004
-
1005
- const secretsToSync: VaultSecretRow[] = [];
1006
- const activeGrants =
1007
- access.mode === "manual"
1008
- ? (await listGrants({ appId })).filter((g) => g.status === "active")
1009
- : [];
1010
-
1011
- if (access.mode === "all-apps") {
1012
- const secrets = await listSecrets();
1013
- for (const secret of secrets) {
1014
- secretsToSync.push(secret);
1015
- }
1016
- } else {
1017
- for (const grant of activeGrants) {
1018
- const secret = await getSecret(grant.secretId, ctx);
1019
- if (secret) {
1020
- secretsToSync.push(secret);
1021
- }
1022
- }
1023
- }
1024
-
1025
- if (secretsToSync.length === 0) {
1026
- return {
1027
- appId,
1028
- accessMode: access.mode,
1029
- synced: 0,
1030
- keys: [],
1031
- credentialStores: [],
1032
- };
1033
- }
1034
-
1035
- const credentialStoreGroups = groupSecretsByTenant(secretsToSync, (row) =>
1036
- ctxForSecretRow(row, ctx),
1037
- );
1038
- const credentialStores: {
1039
- scope: ReturnType<typeof credentialStoreScopeForVaultCtx>["scope"];
1040
- scopeId: string;
1041
- synced: number;
1042
- }[] = [];
1043
- const credentialStoreKeys: string[] = [];
1044
- for (const group of credentialStoreGroups) {
1045
- const result = await syncSecretsToCredentialStore(group.rows, group.ctx);
1046
- credentialStores.push({
1047
- scope: result.scope,
1048
- scopeId: result.scopeId,
1049
- synced: result.keys.length,
1050
- });
1051
- credentialStoreKeys.push(...result.keys);
1052
- }
1053
-
1054
- const vars = secretsToSync.map((secret) => ({
1055
- key: secret.credentialKey,
1056
- value: secret.value,
1057
- }));
1058
- let envVarSync:
1059
- | { status: "synced"; keys: string[] }
1060
- | { status: "skipped"; reason: string }
1061
- | { status: "failed"; reason: string };
1062
-
1063
- if (!isTrustedEnvVarSyncAgentUrl(agent.url)) {
1064
- envVarSync = {
1065
- status: "skipped",
1066
- reason: "env-var sync is limited to localhost or workspace-owned apps",
1067
- };
1068
- } else {
1069
- try {
1070
- const res = await ssrfSafeFetch(
1071
- `${agent.url}/_agent-native/env-vars`,
1072
- {
1073
- method: "POST",
1074
- headers: { "Content-Type": "application/json" },
1075
- body: JSON.stringify({ vars }),
1076
- signal: AbortSignal.timeout(10_000),
1077
- },
1078
- { maxRedirects: 3 },
1079
- );
1080
-
1081
- if (res.ok) {
1082
- const result = await res.json();
1083
- envVarSync = { status: "synced", keys: result.saved || [] };
1084
- } else {
1085
- const err = await res.text().catch(() => "Unknown error");
1086
- envVarSync = { status: "skipped", reason: err };
1087
- }
1088
- } catch (err) {
1089
- envVarSync = {
1090
- status: "failed",
1091
- reason: err instanceof Error ? err.message : String(err),
1092
- };
1093
- }
1094
- }
1095
-
1096
- const syncedKeys = credentialStoreKeys;
1097
- const timestamp = now();
1098
-
1099
- for (const grant of activeGrants) {
1100
- const secret = await getSecret(grant.secretId, ctx);
1101
- if (secret && syncedKeys.includes(secret.credentialKey)) {
1102
- await db
1103
- .update(schema.vaultGrants)
1104
- .set({ syncedAt: timestamp, updatedAt: timestamp })
1105
- .where(eq(schema.vaultGrants.id, grant.id));
1106
- }
1107
- }
1108
-
1109
- await recordVaultAudit({
1110
- action: "secret.synced",
1111
- appId,
1112
- summary: `Synced ${syncedKeys.length} secret(s) to ${appId}: ${syncedKeys.join(", ")}`,
1113
- metadata: {
1114
- syncedKeys,
1115
- accessMode: access.mode,
1116
- credentialStores,
1117
- envVars: envVarSync,
1118
- },
1119
- });
1120
-
1121
- return {
1122
- appId,
1123
- accessMode: access.mode,
1124
- synced: syncedKeys.length,
1125
- keys: syncedKeys,
1126
- credentialStores,
1127
- envVars: envVarSync,
1128
- };
1129
- }
1130
-
1131
932
  export async function listRequests(filter?: { status?: string }) {
1132
933
  const db = getDb();
1133
934
  const ctx = requireVaultCtx();
@@ -1,32 +0,0 @@
1
- declare const _default: import("@agent-native/core/action").ActionDefinition<{
2
- appId: string;
3
- }, {
4
- appId: string;
5
- accessMode: import("../server/lib/vault-store.js").VaultAccessMode;
6
- synced: number;
7
- keys: never[];
8
- credentialStores: never[];
9
- envVars?: undefined;
10
- } | {
11
- appId: string;
12
- accessMode: import("../server/lib/vault-store.js").VaultAccessMode;
13
- synced: number;
14
- keys: string[];
15
- credentialStores: {
16
- scope: ReturnType<typeof import("../server/lib/vault-store.js").credentialStoreScopeForVaultCtx>["scope"];
17
- scopeId: string;
18
- synced: number;
19
- }[];
20
- envVars: {
21
- status: "synced";
22
- keys: string[];
23
- } | {
24
- status: "skipped";
25
- reason: string;
26
- } | {
27
- status: "failed";
28
- reason: string;
29
- };
30
- }>;
31
- export default _default;
32
- //# sourceMappingURL=sync-vault-to-app.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"sync-vault-to-app.d.ts","sourceRoot":"","sources":["../../src/actions/sync-vault-to-app.ts"],"names":[],"mappings":""}