@jini-ai/integrations 0.7.1 → 0.7.3-next.1

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 (121) hide show
  1. package/CHANGELOG.md +2 -2
  2. package/README.md +1 -0
  3. package/dist/api-connections/access-token.js +4 -4
  4. package/dist/api-connections/account-actions.d.ts +10 -4
  5. package/dist/api-connections/account-actions.js +13 -13
  6. package/dist/api-connections/attempt-state.d.ts +11 -5
  7. package/dist/api-connections/attempt-state.js +4 -4
  8. package/dist/api-connections/authorization.d.ts +7 -3
  9. package/dist/api-connections/authorization.js +18 -18
  10. package/dist/api-connections/finish-authorization.d.ts +8 -4
  11. package/dist/api-connections/finish-authorization.js +9 -9
  12. package/dist/api-connections/host.d.ts +30 -32
  13. package/dist/api-connections/host.js +232 -205
  14. package/dist/api-connections/hosted-mcp/contracts.d.ts +1 -1
  15. package/dist/api-connections/hosted-mcp/oauth-row-writes.d.ts +50 -0
  16. package/dist/api-connections/hosted-mcp/oauth-row-writes.js +38 -0
  17. package/dist/api-connections/hosted-mcp/shared-sign-in.d.ts +40 -40
  18. package/dist/api-connections/hosted-mcp/shared-sign-in.js +98 -22
  19. package/dist/api-connections/hosted-mcp/sign-in-configuration.d.ts +29 -0
  20. package/dist/api-connections/hosted-mcp/sign-in-configuration.js +127 -0
  21. package/dist/api-connections/hosted-mcp/sign-in-discovery.d.ts +72 -0
  22. package/dist/api-connections/hosted-mcp/sign-in-discovery.js +131 -0
  23. package/dist/api-connections/hosted-mcp/sign-in-flow.d.ts +42 -0
  24. package/dist/api-connections/hosted-mcp/sign-in-flow.js +50 -0
  25. package/dist/api-connections/hosted-mcp/sign-in-provider.d.ts +103 -0
  26. package/dist/api-connections/hosted-mcp/sign-in-provider.js +142 -0
  27. package/dist/api-connections/hosted-mcp/sign-in-status.d.ts +19 -0
  28. package/dist/api-connections/hosted-mcp/sign-in-status.js +143 -0
  29. package/dist/api-connections/hosted-mcp/sign-in.d.ts +2 -9
  30. package/dist/api-connections/hosted-mcp/sign-in.js +219 -770
  31. package/dist/api-connections/index.js +1 -1
  32. package/dist/api-connections/install-credential.d.ts +4 -2
  33. package/dist/api-connections/install-credential.js +7 -7
  34. package/dist/api-connections/records.d.ts +17 -5
  35. package/dist/api-connections/records.js +5 -5
  36. package/dist/api-connections/request-checks.d.ts +29 -9
  37. package/dist/api-connections/request-checks.js +13 -13
  38. package/dist/api-connections/service.d.ts +1 -1
  39. package/dist/api-connections/service.js +6 -6
  40. package/dist/api-connections/status.d.ts +3 -1
  41. package/dist/api-connections/status.js +3 -3
  42. package/dist/api-connections/token-store/errors.d.ts +3 -1
  43. package/dist/api-connections/token-store/errors.js +1 -1
  44. package/dist/api-connections/token-store/vault-token-store.js +186 -173
  45. package/dist/args.d.ts +4 -1
  46. package/dist/args.js +1 -1
  47. package/dist/credentialed-http/credentialed-request.d.ts +5 -5
  48. package/dist/credentialed-http/credentialed-request.js +8 -8
  49. package/dist/credentialed-http/response-redaction.d.ts +18 -4
  50. package/dist/credentialed-http/response-redaction.js +7 -7
  51. package/dist/credentialed-http/sets/vault-repo.js +5 -1
  52. package/dist/credentialed-http/tools/credential-copy-tool.js +20 -15
  53. package/dist/credentialed-http/tools/tool-registrations.js +272 -249
  54. package/dist/media-providers/catalog.d.ts +1 -0
  55. package/dist/media-providers/catalog.js +1 -0
  56. package/dist/media-providers/dispatch/async-operation-store.d.ts +6 -4
  57. package/dist/media-providers/dispatch/async-operation-store.js +100 -88
  58. package/dist/media-providers/dispatch/context.js +1 -1
  59. package/dist/media-providers/dispatch/engine.d.ts +5 -1
  60. package/dist/media-providers/dispatch/engine.js +2 -2
  61. package/dist/media-providers/dispatch/index.d.ts +1 -1
  62. package/dist/media-providers/dispatch/index.js +1 -1
  63. package/dist/media-providers/dispatch/node.d.ts +1 -1
  64. package/dist/media-providers/dispatch/node.js +1 -1
  65. package/dist/media-providers/dispatch/openai-compatible.d.ts +50 -11
  66. package/dist/media-providers/dispatch/openai-compatible.js +21 -17
  67. package/dist/media-providers/dispatch/operation-runtime.js +18 -18
  68. package/dist/media-providers/dispatch/outbound.d.ts +2 -2
  69. package/dist/media-providers/dispatch/outbound.js +1 -1
  70. package/dist/media-providers/dispatch/polling-adapter.d.ts +1 -1
  71. package/dist/media-providers/dispatch/providers/aihubmix-shared.d.ts +20 -6
  72. package/dist/media-providers/dispatch/providers/aihubmix-shared.js +8 -8
  73. package/dist/media-providers/dispatch/providers/aihubmix.js +12 -12
  74. package/dist/media-providers/dispatch/providers/custom-image.js +4 -4
  75. package/dist/media-providers/dispatch/providers/fishaudio.js +2 -9
  76. package/dist/media-providers/dispatch/providers/grok.js +5 -19
  77. package/dist/media-providers/dispatch/providers/imagerouter-video-async.js +22 -20
  78. package/dist/media-providers/dispatch/providers/imagerouter.js +7 -21
  79. package/dist/media-providers/dispatch/providers/minimax.js +2 -9
  80. package/dist/media-providers/dispatch/providers/nanobanana.js +2 -2
  81. package/dist/media-providers/dispatch/providers/openai.js +6 -6
  82. package/dist/media-providers/dispatch/providers/openrouter.js +4 -4
  83. package/dist/media-providers/dispatch/providers/senseaudio.js +5 -19
  84. package/dist/media-providers/dispatch/providers/volcengine.js +5 -12
  85. package/dist/media-providers/dispatch/response-parsers.js +3 -3
  86. package/dist/media-providers/dispatch/sqlite-async-operation-store.d.ts +1 -1
  87. package/dist/media-providers/dispatch/sqlite-async-operation-store.js +31 -5
  88. package/dist/media-providers/dispatch/ssrf-guard.js +5 -12
  89. package/dist/media-providers/dispatch/stub.js +2 -2
  90. package/dist/media-providers/dispatch/vendor-adapter.js +2 -2
  91. package/dist/media-providers/image-model-ids.d.ts +36 -0
  92. package/dist/media-providers/image-model-ids.js +24 -0
  93. package/dist/media-providers/sqlite-driver.adapter.d.ts +1 -1
  94. package/dist/media-providers/sqlite-task-store.d.ts +2 -2
  95. package/dist/media-providers/sqlite-task-store.js +31 -4
  96. package/dist/media-providers/task-lifecycle.d.ts +17 -4
  97. package/dist/media-providers/task-lifecycle.js +4 -4
  98. package/dist/media-providers/task-store.js +28 -24
  99. package/dist/media-providers/ui-defaults.d.ts +7 -0
  100. package/dist/media-providers/ui-defaults.js +11 -17
  101. package/dist/saved-requests/types.d.ts +1 -1
  102. package/dist/webhooks/delivery.js +31 -27
  103. package/dist/webhooks/ports.d.ts +4 -1
  104. package/dist/webhooks/subscriptions.d.ts +7 -2
  105. package/dist/webhooks/subscriptions.js +30 -37
  106. package/dist/webhooks/tools/agent-tools.d.ts +82 -0
  107. package/dist/webhooks/tools/agent-tools.js +120 -0
  108. package/dist/webhooks/tools/index.d.ts +7 -0
  109. package/dist/webhooks/tools/index.js +5 -0
  110. package/dist/webhooks/tools/tool-handlers.d.ts +22 -0
  111. package/dist/webhooks/tools/tool-handlers.js +154 -0
  112. package/dist/webhooks/tools/tool-handlers.types.d.ts +64 -0
  113. package/dist/webhooks/tools/tool-handlers.types.js +2 -0
  114. package/dist/webhooks/tools/tool-registrations.d.ts +35 -0
  115. package/dist/webhooks/tools/tool-registrations.js +95 -0
  116. package/dist/webhooks/tools/tool-views.d.ts +62 -0
  117. package/dist/webhooks/tools/tool-views.js +50 -0
  118. package/dist/webhooks/types.d.ts +2 -0
  119. package/dist/webhooks/worker.d.ts +7 -4
  120. package/dist/webhooks/worker.js +22 -20
  121. package/package.json +16 -18
@@ -17,196 +17,209 @@ const LEASE_TTL_MS = 30_000;
17
17
  const LOAD_OBSERVATION_WINDOW_MS = 60_000;
18
18
  /** Disconnect and install must win over concurrent lease writes; each retry re-reads the newest revision. */
19
19
  const WRITE_ATTEMPTS = 3;
20
+ const identity = ({ deps }, { key }) => ({ ...deps.vaultScope, id: key });
21
+ async function openRecord(ctx, { key }) {
22
+ const found = await ctx.deps.vault.get(identity(ctx, { key }));
23
+ if (found === null)
24
+ return null;
25
+ const meta = readRecordMeta({ meta: found.summary.meta });
26
+ return { revision: found.summary.revision, meta, payload: parseTokenPayload({ payload: found.payload, key, owner: ctx.deps.owner }) };
27
+ }
28
+ function recentLoadsOf(ctx, { key }) {
29
+ const nowMs = ctx.deps.clock.nowMs();
30
+ return (ctx.loads.get(key) ?? []).filter(entry => nowMs - entry.atMs < LOAD_OBSERVATION_WINDOW_MS);
31
+ }
32
+ function observeLoad(ctx, { key, generation }) {
33
+ ctx.loads.set(key, [...recentLoadsOf(ctx, { key }), { generation, atMs: ctx.deps.clock.nowMs() }]);
34
+ }
35
+ function takeRecentLoads(ctx, { key }) {
36
+ const recent = recentLoadsOf(ctx, { key });
37
+ ctx.loads.delete(key);
38
+ return recent;
39
+ }
40
+ async function writeRecord(ctx, { key, required }) {
41
+ // The vault keeps labels unique per scope, and one scope holds several rows per connection
42
+ // (main and staged keys, other plugins' connections), so the label is the unique, non-secret key.
43
+ await ctx.deps.vault.put({ ...identity(ctx, { key }), expectedRevision: required.revision, provider: null,
44
+ label: key, meta: buildRecordMeta({ meta: required.meta }), payload: required.payload });
45
+ }
46
+ // Every token write re-proves the lease and the generation immediately before the CAS write.
47
+ async function fencedWrite(ctx, { key, required }) {
48
+ const { deps } = ctx;
49
+ const lease = ctx.held.get(key);
50
+ if (lease === undefined)
51
+ throw new OAuthTokenStoreError({ code: "lease-not-held" });
52
+ if (await deps.readGeneration({ key }) !== lease.generation)
53
+ throw new OAuthTokenStoreError({ code: "stale-generation" });
54
+ const record = await openRecord(ctx, { key });
55
+ if (record === null || record.meta.leaseHolder !== lease.holder)
56
+ throw new OAuthTokenStoreError({ code: "lease-lost" });
57
+ const payload = buildTokenPayload({ key, owner: deps.owner, generation: lease.generation, tokens: required.tokens });
58
+ try {
59
+ await writeRecord(ctx, {
60
+ key,
61
+ required: { revision: record.revision, meta: { ...record.meta, status: required.status }, payload },
62
+ });
63
+ }
64
+ catch (error) {
65
+ throw deps.isVaultConflict(error) ? new OAuthTokenStoreError({ code: "lease-lost" }, { cause: error }) : error;
66
+ }
67
+ }
68
+ async function claimLease(ctx, { key, required }) {
69
+ const { deps } = ctx;
70
+ const leaseFields = { leaseHolder: required.holder, leaseExpiresAtMs: deps.clock.nowMs() + LEASE_TTL_MS };
71
+ try {
72
+ if (required.record === null) {
73
+ await writeRecord(ctx, {
74
+ key,
75
+ required: { revision: null, meta: { status: "active", ...leaseFields },
76
+ payload: buildTokenPayload({ key, owner: deps.owner, generation: required.generation, tokens: null }) },
77
+ });
78
+ }
79
+ else {
80
+ await deps.vault.patchMeta({ ...identity(ctx, { key }), expectedRevision: required.record.revision, patch: leaseFields });
81
+ }
82
+ return true;
83
+ }
84
+ catch (error) {
85
+ if (deps.isVaultConflict(error))
86
+ return false;
87
+ throw error;
88
+ }
89
+ }
90
+ // Lease fields are kept: a refresher holding the lease for an older generation is refused by
91
+ // its own generation check or by this write's revision change, and then releases as usual.
92
+ // The row an install replaces; see `readReplaceableGeneration` for which rows qualify.
93
+ async function openInstallTarget(ctx, { key }) {
94
+ const found = await ctx.deps.vault.get(identity(ctx, { key }));
95
+ if (found === null)
96
+ return { revision: null, generation: null, meta: { status: "active", leaseHolder: null, leaseExpiresAtMs: null } };
97
+ return { revision: found.summary.revision, generation: readReplaceableGeneration({ payload: found.payload, key, owner: ctx.deps.owner }),
98
+ meta: readRecordMeta({ meta: found.summary.meta }) };
99
+ }
100
+ async function installOnce(ctx, { key, required }) {
101
+ const { deps } = ctx;
102
+ if (await deps.readGeneration({ key }) !== required.generation)
103
+ throw new OAuthTokenStoreError({ code: "stale-generation" });
104
+ const target = await openInstallTarget(ctx, { key });
105
+ // The live generation moved on after the check above and a newer install already landed.
106
+ if (target.generation !== null && target.generation > required.generation)
107
+ throw new OAuthTokenStoreError({ code: "stale-generation" });
108
+ try {
109
+ await writeRecord(ctx, {
110
+ key,
111
+ required: { revision: target.revision, meta: { ...target.meta, status: "active" },
112
+ payload: buildTokenPayload({ key, owner: deps.owner, generation: required.generation, tokens: required.tokens }) },
113
+ });
114
+ return true;
115
+ }
116
+ catch (error) {
117
+ if (deps.isVaultConflict(error))
118
+ return false;
119
+ throw error;
120
+ }
121
+ }
122
+ // Needs only the revision: a row this owner can no longer open (another client id, malformed)
123
+ // must still be removable, or a disconnect could never clear it.
124
+ async function deleteOnce(ctx, { key }) {
125
+ const found = await ctx.deps.vault.get(identity(ctx, { key }));
126
+ if (found === null)
127
+ return true;
128
+ try {
129
+ await ctx.deps.vault.delete({ ...identity(ctx, { key }), expectedRevision: found.summary.revision });
130
+ return true;
131
+ }
132
+ catch (error) {
133
+ if (ctx.deps.isVaultConflict(error))
134
+ return false;
135
+ throw error;
136
+ }
137
+ }
138
+ async function tryAcquireRefreshLease(ctx, { key }) {
139
+ const { deps } = ctx;
140
+ const recentLoads = takeRecentLoads(ctx, { key });
141
+ const generation = await deps.readGeneration({ key });
142
+ if (recentLoads.some(entry => entry.generation !== generation))
143
+ return false;
144
+ const record = await openRecord(ctx, { key });
145
+ const leaseExpiresAtMs = record?.meta.leaseExpiresAtMs ?? null;
146
+ if (record?.meta.leaseHolder && leaseExpiresAtMs !== null && leaseExpiresAtMs > deps.clock.nowMs())
147
+ return false;
148
+ const holder = randomUUID();
149
+ if (!await claimLease(ctx, { key, required: { record, generation, holder } }))
150
+ return false;
151
+ ctx.held.set(key, { holder, generation });
152
+ return true;
153
+ }
154
+ async function releaseRefreshLease(ctx, { key }) {
155
+ const lease = ctx.held.get(key);
156
+ if (lease === undefined)
157
+ return;
158
+ ctx.held.delete(key);
159
+ const record = await openRecord(ctx, { key });
160
+ if (record === null || record.meta.leaseHolder !== lease.holder)
161
+ return;
162
+ try {
163
+ await ctx.deps.vault.patchMeta({ ...identity(ctx, { key }), expectedRevision: record.revision, patch: { leaseHolder: null, leaseExpiresAtMs: null } });
164
+ }
165
+ catch (error) {
166
+ // A concurrent writer changed the row; the lease then lapses on its own expiry.
167
+ if (!ctx.deps.isVaultConflict(error))
168
+ throw error;
169
+ }
170
+ }
171
+ async function loadCurrent(ctx, { key }) {
172
+ const generation = await ctx.deps.readGeneration({ key });
173
+ const record = await openRecord(ctx, { key });
174
+ // Tokens sealed under an older generation belong to a disconnected or switched account.
175
+ if (record === null || record.payload.generation !== generation)
176
+ return null;
177
+ observeLoad(ctx, { key, generation });
178
+ return record.payload.tokens;
179
+ }
180
+ async function installTokens(ctx, { key, tokens, generation }) {
181
+ const parsed = parseTokenSet({ value: tokens });
182
+ for (let attempt = 0; attempt < WRITE_ATTEMPTS; attempt += 1) {
183
+ if (await installOnce(ctx, { key, required: { tokens: parsed, generation } }))
184
+ return;
185
+ }
186
+ throw new OAuthTokenStoreError({ code: "write-conflict" });
187
+ }
188
+ async function deleteTokens(ctx, { key }) {
189
+ ctx.loads.delete(key);
190
+ for (let attempt = 0; attempt < WRITE_ATTEMPTS; attempt += 1) {
191
+ if (await deleteOnce(ctx, { key }))
192
+ return;
193
+ }
194
+ throw new OAuthTokenStoreError({ code: "write-conflict" });
195
+ }
20
196
  /** Creates the store for one connection owner.
21
197
  * @throws OAuthTokenStoreError `configuration` when the vault scope names another workspace. */
22
198
  export function createVaultOAuthTokenStore(deps, _optionalArgs = {}) {
23
- const { vault, vaultScope, owner, readGeneration, clock } = deps;
24
- const isConflict = deps.isVaultConflict;
25
- if (vaultScope.workspaceId !== owner.workspaceId)
199
+ if (deps.vaultScope.workspaceId !== deps.owner.workspaceId)
26
200
  throw new OAuthTokenStoreError({ code: "configuration" });
27
- // Leases this instance holds, with the generation recorded at acquisition (the write fence).
28
- const held = new Map();
29
- // Generations recent loads returned; a lease is refused if any differs from the live one,
30
- // because the refresher would then be refreshing tokens of a connection that has moved on.
31
- const loads = new Map();
32
- const identity = (key) => ({ ...vaultScope, id: key });
33
- const open = async (key) => {
34
- const found = await vault.get(identity(key));
35
- if (found === null)
36
- return null;
37
- const meta = readRecordMeta({ meta: found.summary.meta });
38
- return { revision: found.summary.revision, meta, payload: parseTokenPayload({ payload: found.payload, key, owner }) };
39
- };
40
- const observeLoad = (key, generation) => {
41
- const nowMs = clock.nowMs();
42
- const recent = (loads.get(key) ?? []).filter(entry => nowMs - entry.atMs < LOAD_OBSERVATION_WINDOW_MS);
43
- loads.set(key, [...recent, { generation, atMs: nowMs }]);
44
- };
45
- const takeRecentLoads = (key) => {
46
- const nowMs = clock.nowMs();
47
- const recent = (loads.get(key) ?? []).filter(entry => nowMs - entry.atMs < LOAD_OBSERVATION_WINDOW_MS);
48
- loads.delete(key);
49
- return recent;
50
- };
51
- const writeRecord = async (key, required) => {
52
- // The vault keeps labels unique per scope, and one scope holds several rows per connection
53
- // (main and staged keys, other plugins' connections), so the label is the unique, non-secret key.
54
- await vault.put({ ...identity(key), expectedRevision: required.revision, provider: null,
55
- label: key, meta: buildRecordMeta({ meta: required.meta }), payload: required.payload });
56
- };
57
- // Every token write re-proves the lease and the generation immediately before the CAS write.
58
- const fencedWrite = async (key, required) => {
59
- const lease = held.get(key);
60
- if (lease === undefined)
61
- throw new OAuthTokenStoreError({ code: "lease-not-held" });
62
- if (await readGeneration({ key }) !== lease.generation)
63
- throw new OAuthTokenStoreError({ code: "stale-generation" });
64
- const record = await open(key);
65
- if (record === null || record.meta.leaseHolder !== lease.holder)
66
- throw new OAuthTokenStoreError({ code: "lease-lost" });
67
- const payload = buildTokenPayload({ key, owner, generation: lease.generation, tokens: required.tokens });
68
- try {
69
- await writeRecord(key, { revision: record.revision, meta: { ...record.meta, status: required.status }, payload });
70
- }
71
- catch (error) {
72
- throw isConflict(error) ? new OAuthTokenStoreError({ code: "lease-lost" }, { cause: error }) : error;
73
- }
74
- };
75
- const claimLease = async (key, required) => {
76
- const leaseFields = { leaseHolder: required.holder, leaseExpiresAtMs: clock.nowMs() + LEASE_TTL_MS };
77
- try {
78
- if (required.record === null) {
79
- await writeRecord(key, { revision: null, meta: { status: "active", ...leaseFields },
80
- payload: buildTokenPayload({ key, owner, generation: required.generation, tokens: null }) });
81
- }
82
- else {
83
- await vault.patchMeta({ ...identity(key), expectedRevision: required.record.revision, patch: leaseFields });
84
- }
85
- return true;
86
- }
87
- catch (error) {
88
- if (isConflict(error))
89
- return false;
90
- throw error;
91
- }
92
- };
93
- // Lease fields are kept: a refresher holding the lease for an older generation is refused by
94
- // its own generation check or by this write's revision change, and then releases as usual.
95
- // The row an install replaces; see `readReplaceableGeneration` for which rows qualify.
96
- const openInstallTarget = async (key) => {
97
- const found = await vault.get(identity(key));
98
- if (found === null)
99
- return { revision: null, generation: null, meta: { status: "active", leaseHolder: null, leaseExpiresAtMs: null } };
100
- return { revision: found.summary.revision, generation: readReplaceableGeneration({ payload: found.payload, key, owner }),
101
- meta: readRecordMeta({ meta: found.summary.meta }) };
102
- };
103
- const installOnce = async (key, required) => {
104
- if (await readGeneration({ key }) !== required.generation)
105
- throw new OAuthTokenStoreError({ code: "stale-generation" });
106
- const target = await openInstallTarget(key);
107
- // The live generation moved on after the check above and a newer install already landed.
108
- if (target.generation !== null && target.generation > required.generation)
109
- throw new OAuthTokenStoreError({ code: "stale-generation" });
110
- try {
111
- await writeRecord(key, { revision: target.revision, meta: { ...target.meta, status: "active" },
112
- payload: buildTokenPayload({ key, owner, generation: required.generation, tokens: required.tokens }) });
113
- return true;
114
- }
115
- catch (error) {
116
- if (isConflict(error))
117
- return false;
118
- throw error;
119
- }
120
- };
121
- // Needs only the revision: a row this owner can no longer open (another client id, malformed)
122
- // must still be removable, or a disconnect could never clear it.
123
- const deleteOnce = async (key) => {
124
- const found = await vault.get(identity(key));
125
- if (found === null)
126
- return true;
127
- try {
128
- await vault.delete({ ...identity(key), expectedRevision: found.summary.revision });
129
- return true;
130
- }
131
- catch (error) {
132
- if (isConflict(error))
133
- return false;
134
- throw error;
135
- }
136
- };
201
+ const ctx = { deps, held: new Map(), loads: new Map() };
137
202
  return {
138
- async load({ key }) {
139
- const generation = await readGeneration({ key });
140
- const record = await open(key);
141
- // Tokens sealed under an older generation belong to a disconnected or switched account.
142
- if (record === null || record.payload.generation !== generation)
143
- return null;
144
- observeLoad(key, generation);
145
- return record.payload.tokens;
146
- },
203
+ load: ({ key }) => loadCurrent(ctx, { key }),
147
204
  // Generation-agnostic on purpose: a disconnect disables the credential by moving the
148
205
  // generation, and only that disabled credential can still revoke the grant. Not recorded as a
149
206
  // load, so it never feeds the refresh-lease decision.
150
207
  async loadForRevocation({ key }) {
151
- const record = await open(key);
208
+ const record = await openRecord(ctx, { key });
152
209
  return record?.payload.tokens ?? null;
153
210
  },
154
211
  async persist({ key, tokens }) {
155
- await fencedWrite(key, { status: "active", tokens: parseTokenSet({ value: tokens }) });
156
- },
157
- async install({ key, tokens, generation }) {
158
- const parsed = parseTokenSet({ value: tokens });
159
- for (let attempt = 0; attempt < WRITE_ATTEMPTS; attempt += 1) {
160
- if (await installOnce(key, { tokens: parsed, generation }))
161
- return;
162
- }
163
- throw new OAuthTokenStoreError({ code: "write-conflict" });
212
+ await fencedWrite(ctx, { key, required: { status: "active", tokens: parseTokenSet({ value: tokens }) } });
164
213
  },
214
+ install: ({ key, tokens, generation }) => installTokens(ctx, { key, tokens, generation }),
165
215
  // The reason is not stored: callers may pass provider text, and status must stay secret-free.
166
216
  // The refresh token is dead after invalid_grant, so the tokens are cleared with the status change.
167
217
  async markNeedsReauth({ key }) {
168
- await fencedWrite(key, { status: "reconnect-required", tokens: null });
169
- },
170
- async tryAcquireRefreshLease({ key }) {
171
- const recentLoads = takeRecentLoads(key);
172
- const generation = await readGeneration({ key });
173
- if (recentLoads.some(entry => entry.generation !== generation))
174
- return false;
175
- const record = await open(key);
176
- const leaseExpiresAtMs = record?.meta.leaseExpiresAtMs ?? null;
177
- if (record?.meta.leaseHolder && leaseExpiresAtMs !== null && leaseExpiresAtMs > clock.nowMs())
178
- return false;
179
- const holder = randomUUID();
180
- if (!await claimLease(key, { record, generation, holder }))
181
- return false;
182
- held.set(key, { holder, generation });
183
- return true;
184
- },
185
- async releaseRefreshLease({ key }) {
186
- const lease = held.get(key);
187
- if (lease === undefined)
188
- return;
189
- held.delete(key);
190
- const record = await open(key);
191
- if (record === null || record.meta.leaseHolder !== lease.holder)
192
- return;
193
- try {
194
- await vault.patchMeta({ ...identity(key), expectedRevision: record.revision, patch: { leaseHolder: null, leaseExpiresAtMs: null } });
195
- }
196
- catch (error) {
197
- // A concurrent writer changed the row; the lease then lapses on its own expiry.
198
- if (!isConflict(error))
199
- throw error;
200
- }
201
- },
202
- async delete({ key }) {
203
- loads.delete(key);
204
- for (let attempt = 0; attempt < WRITE_ATTEMPTS; attempt += 1) {
205
- if (await deleteOnce(key))
206
- return;
207
- }
208
- throw new OAuthTokenStoreError({ code: "write-conflict" });
218
+ await fencedWrite(ctx, { key, required: { status: "reconnect-required", tokens: null } });
209
219
  },
220
+ tryAcquireRefreshLease: ({ key }) => tryAcquireRefreshLease(ctx, { key }),
221
+ releaseRefreshLease: ({ key }) => releaseRefreshLease(ctx, { key }),
222
+ delete: ({ key }) => deleteTokens(ctx, { key }),
210
223
  };
211
224
  }
212
225
  //# sourceMappingURL=vault-token-store.js.map
package/dist/args.d.ts CHANGED
@@ -4,5 +4,8 @@ export type RequiredArgs<T> = Pick<T, {
4
4
  }[keyof T]>;
5
5
  export type OptionalArgs<T> = Pick<T, Exclude<keyof T, keyof RequiredArgs<T>>>;
6
6
  /** Package-local composition helper; public APIs expose the two records directly. */
7
- export declare function partitionArgs<T extends object, K extends keyof T>(value: T, requiredKeys: readonly K[]): [Pick<T, K>, Omit<T, K>];
7
+ export declare function partitionArgs<T extends object, K extends keyof T>({ value, requiredKeys }: {
8
+ value: T;
9
+ requiredKeys: readonly K[];
10
+ }, _optional?: Record<string, never>): [Pick<T, K>, Omit<T, K>];
8
11
  //# sourceMappingURL=args.d.ts.map
package/dist/args.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /** Package-local composition helper; public APIs expose the two records directly. */
2
- export function partitionArgs(value, requiredKeys) {
2
+ export function partitionArgs({ value, requiredKeys }, _optional = {}) {
3
3
  const required = {};
4
4
  const optional = {};
5
5
  for (const key of Object.keys(value)) {
@@ -106,16 +106,16 @@ export interface CredentialConnectionProbeInput {
106
106
  readonly method?: "GET";
107
107
  }
108
108
  /** Send one bodyless GET through the guarded HTTP port without following redirects.
109
- * @param required Plaintext connection, trusted host-resolved URL and auth-scheme rules.
110
- * @param options Guarded HTTP client; owns DNS/address policy, peer pinning and response bounds.
109
+ * @param required Plaintext connection, trusted host-resolved URL, auth-scheme rules and guarded HTTP client.
110
+ * The client owns DNS/address policy, peer pinning and response bounds.
111
111
  * @returns Only ok/refused/unavailable; no bodies, headers, URLs, secrets or transport errors.
112
112
  * @throws CredentialedRequestValidationError with value-free text for non-GET or malformed URLs.
113
113
  * @complexity One bounded HTTP send plus O(r) auth matching for r supplied scheme rules.
114
- * @example await probeCredentialConnection({ connection, url, schemes }, { httpClient });
114
+ * @example await probeCredentialConnection({ connection, url, schemes, httpClient });
115
115
  */
116
- export declare function probeCredentialConnection(required: CredentialConnectionProbeInput, options: {
116
+ export declare function probeCredentialConnection(required: CredentialConnectionProbeInput & {
117
117
  httpClient: HttpClientPort;
118
- }): Promise<CredentialConnectionProbeStatus>;
118
+ }, _optional?: Record<string, never>): Promise<CredentialConnectionProbeStatus>;
119
119
  export interface CustomCredentialVerificationResult {
120
120
  readonly status: CustomCredentialCheckStatus;
121
121
  readonly message: string;
@@ -213,14 +213,14 @@ async function resolveCredentialOrThrow(deps, input) {
213
213
  return resolved;
214
214
  }
215
215
  /** Send one bodyless GET through the guarded HTTP port without following redirects.
216
- * @param required Plaintext connection, trusted host-resolved URL and auth-scheme rules.
217
- * @param options Guarded HTTP client; owns DNS/address policy, peer pinning and response bounds.
216
+ * @param required Plaintext connection, trusted host-resolved URL, auth-scheme rules and guarded HTTP client.
217
+ * The client owns DNS/address policy, peer pinning and response bounds.
218
218
  * @returns Only ok/refused/unavailable; no bodies, headers, URLs, secrets or transport errors.
219
219
  * @throws CredentialedRequestValidationError with value-free text for non-GET or malformed URLs.
220
220
  * @complexity One bounded HTTP send plus O(r) auth matching for r supplied scheme rules.
221
- * @example await probeCredentialConnection({ connection, url, schemes }, { httpClient });
221
+ * @example await probeCredentialConnection({ connection, url, schemes, httpClient });
222
222
  */
223
- export async function probeCredentialConnection(required, options) {
223
+ export async function probeCredentialConnection(required, _optional = {}) {
224
224
  if (required.method !== undefined && required.method !== "GET") {
225
225
  throw new CredentialedRequestValidationError({ message: "credential probes only support GET" });
226
226
  }
@@ -232,7 +232,7 @@ export async function probeCredentialConnection(required, options) {
232
232
  // URL parse errors may contain their input; probe failures must never echo caller values.
233
233
  throw new CredentialedRequestValidationError({ message: "credential probe requires an absolute HTTP(S) URL without embedded credentials" });
234
234
  }
235
- return classifyCredentialProbeStatus(await sendCredentialGet({ ...required, url, httpClient: options.httpClient }, { strict: true }));
235
+ return classifyCredentialProbeStatus(await sendCredentialGet({ ...required, url }, { strict: true }));
236
236
  }
237
237
  /** One bodyless authenticated GET shared by the probe and verification. Returns the HTTP status,
238
238
  * or 0 when the transport failed; transport errors are dropped because they can echo request values.
@@ -381,7 +381,7 @@ function failTransport(required, optional) {
381
381
  if (egressRefusal !== undefined)
382
382
  throw err;
383
383
  const detail = err instanceof Error ? err.message : String(err);
384
- throw new CredentialedRequestTransportError({ message: `request to '${auditBase.label}' failed: ${resolveRedactedResponseBody(detail, redaction.connection.token, redaction.secrets, false)}` });
384
+ throw new CredentialedRequestTransportError({ message: `request to '${auditBase.label}' failed: ${resolveRedactedResponseBody({ bodyText: detail, token: redaction.connection.token, secrets: redaction.secrets, bodyTruncated: false })}` });
385
385
  }
386
386
  // Only a host-recognized refusal yields audit detail; any other failure, or no policy, yields none.
387
387
  function describeEgressRefusal(err, policy) {
@@ -395,7 +395,7 @@ function buildExecutedResult(required, optional) {
395
395
  return {
396
396
  executed: true,
397
397
  status: response.status,
398
- headers: redactResponseHeaders(response.headers, redaction.secrets),
398
+ headers: redactResponseHeaders({ headers: response.headers, secrets: redaction.secrets }),
399
399
  bodyText: redactExecutedBody({ response, redaction }, optional),
400
400
  ...(authDiagnostic ? { authDiagnostic } : {}),
401
401
  };
@@ -412,6 +412,6 @@ function redactExecutedBody({ response, redaction }, options = {}) {
412
412
  throw new CredentialedRequestValidationError({ message: "JSON response must be valid" });
413
413
  }
414
414
  }
415
- return resolveRedactedResponseBody(response.bodyText, redaction.connection.token, redaction.secrets, response.bodyTruncated === true);
415
+ return resolveRedactedResponseBody({ bodyText: response.bodyText, token: redaction.connection.token, secrets: redaction.secrets, bodyTruncated: response.bodyTruncated === true });
416
416
  }
417
417
  //# sourceMappingURL=credentialed-request.js.map
@@ -1,7 +1,21 @@
1
- export declare function redactResponseHeaders(headers: Readonly<Record<string, string>>, secrets: readonly string[]): Record<string, string>;
2
- export declare function redactSecretSubstrings(text: string, secrets: readonly string[]): string;
3
- export declare function redactTruncatedTail(body: string, secrets: readonly string[]): string;
4
- export declare function resolveRedactedResponseBody(bodyText: string, token: string, secrets: readonly string[], bodyTruncated: boolean): string;
1
+ export declare function redactResponseHeaders({ headers, secrets }: {
2
+ headers: Readonly<Record<string, string>>;
3
+ secrets: readonly string[];
4
+ }, _optional?: Record<string, never>): Record<string, string>;
5
+ export declare function redactSecretSubstrings({ text, secrets }: {
6
+ text: string;
7
+ secrets: readonly string[];
8
+ }, _optional?: Record<string, never>): string;
9
+ export declare function redactTruncatedTail({ body, secrets }: {
10
+ body: string;
11
+ secrets: readonly string[];
12
+ }, _optional?: Record<string, never>): string;
13
+ export declare function resolveRedactedResponseBody({ bodyText, token, secrets, bodyTruncated }: {
14
+ bodyText: string;
15
+ token: string;
16
+ secrets: readonly string[];
17
+ bodyTruncated: boolean;
18
+ }, _optional?: Record<string, never>): string;
5
19
  /** Opt-in JSON release boundary: decode escaped strings before using the same credential-secret
6
20
  * owner. Scrubbing only serialized bytes misses a provider echo such as `\u0073ecret-token`.
7
21
  * Callers must reject truncated responses first. Malformed JSON or secrets in keys/numbers throw;
@@ -17,7 +17,7 @@ const MIN_SAFE_BODY_REDACTION_TOKEN_LENGTH = 8;
17
17
  const BODY_WITHHELD_SHORT_TOKEN_MARKER = "[body withheld: credential too short to redact safely]";
18
18
  // Match secrets embedded in diagnostic header values too, not just values equal to a full secret.
19
19
  // Whole-header removal has no partial-mangling failure mode and therefore applies at any length.
20
- export function redactResponseHeaders(headers, secrets) {
20
+ export function redactResponseHeaders({ headers, secrets }, _optional = {}) {
21
21
  const result = {};
22
22
  for (const [key, value] of Object.entries(headers)) {
23
23
  const forbidden = FORBIDDEN_RESPONSE_HEADER_NAMES.has(key.trim().toLowerCase());
@@ -29,7 +29,7 @@ export function redactResponseHeaders(headers, secrets) {
29
29
  }
30
30
  // Reflecting responses must not send injected credentials back through the model; retain all other
31
31
  // provider text instead of replacing the provider's answer with an authentication diagnosis.
32
- export function redactSecretSubstrings(text, secrets) {
32
+ export function redactSecretSubstrings({ text, secrets }, _optional = {}) {
33
33
  return secrets.reduce((acc, secret) => (secret === "" ? acc : acc.split(secret).join(REDACTED_MARKER)), text);
34
34
  }
35
35
  // One-to-three-character suffix matches are too ambiguous to identify a cut-off secret. This
@@ -38,7 +38,7 @@ const MIN_SAFE_TRUNCATED_TAIL_PREFIX_LENGTH = 4;
38
38
  // A size cap can cut a reflected secret mid-token, so whole-secret replacement alone leaks its
39
39
  // prefix. Use the longest matching suffix across all secrets to remove the whole fragment; only
40
40
  // truncated bodies qualify, since matching complete bodies could remove innocent trailing text.
41
- export function redactTruncatedTail(body, secrets) {
41
+ export function redactTruncatedTail({ body, secrets }, _optional = {}) {
42
42
  let longestMatch = 0;
43
43
  for (const secret of secrets) {
44
44
  for (let len = Math.min(secret.length, body.length); len >= MIN_SAFE_TRUNCATED_TAIL_PREFIX_LENGTH; len--) {
@@ -52,11 +52,11 @@ export function redactTruncatedTail(body, secrets) {
52
52
  }
53
53
  // Gate on the raw token: a scheme-prefixed header is longer and cannot make a short token safe.
54
54
  // The second pass is conditional because a complete response has no cap-cut fragment to repair.
55
- export function resolveRedactedResponseBody(bodyText, token, secrets, bodyTruncated) {
55
+ export function resolveRedactedResponseBody({ bodyText, token, secrets, bodyTruncated }, _optional = {}) {
56
56
  if (token.length < MIN_SAFE_BODY_REDACTION_TOKEN_LENGTH)
57
57
  return BODY_WITHHELD_SHORT_TOKEN_MARKER;
58
- const redacted = redactSecretSubstrings(bodyText, secrets);
59
- return bodyTruncated ? redactTruncatedTail(redacted, secrets) : redacted;
58
+ const redacted = redactSecretSubstrings({ text: bodyText, secrets });
59
+ return bodyTruncated ? redactTruncatedTail({ body: redacted, secrets }) : redacted;
60
60
  }
61
61
  /** Opt-in JSON release boundary: decode escaped strings before using the same credential-secret
62
62
  * owner. Scrubbing only serialized bytes misses a provider echo such as `\u0073ecret-token`.
@@ -73,7 +73,7 @@ export function redactJsonResponseBody({ bodyText, token, secrets }, _options =
73
73
  if (typeof value === "number" && secrets.some(secret => secret !== "" && String(value).includes(secret)))
74
74
  throw new TypeError("JSON response number contains a credential");
75
75
  if (typeof value === "string")
76
- return redactSecretSubstrings(value, secrets);
76
+ return redactSecretSubstrings({ text: value, secrets });
77
77
  return value;
78
78
  });
79
79
  return JSON.stringify(decoded);
@@ -113,13 +113,17 @@ export class CredentialSetVaultRepo {
113
113
  }
114
114
  }
115
115
  function compatibilityVaultRow({ record, expectedRevision, existing, policy }, _options = {}) {
116
- const kind = existing?.kind === "custom" ? "custom" : "vendor";
116
+ const kind = compatibilityKind({ existing });
117
117
  return { ...credentialSetVaultScope({ ...record, kind, ownerKey: policy.ownerKey }), id: record.id, provider: null, label: record.label,
118
118
  sealed: record.sealed, isDefault: existing?.isDefault ?? false, revision: (expectedRevision ?? 0) + 1,
119
119
  ...compatibilityTokenHints({ record, ...(existing ? { existing } : {}) }),
120
120
  meta: compatibilityVaultMeta({ record, kind, policy, ...(existing ? { existing } : {}) }),
121
121
  createdAt: existing?.createdAt ?? record.createdAt, updatedAt: record.updatedAt };
122
122
  }
123
+ /** An existing custom row stays custom; every other write is a vendor row. */
124
+ function compatibilityKind({ existing }, _options = {}) {
125
+ return existing?.kind === "custom" ? "custom" : "vendor";
126
+ }
123
127
  function compatibilityVaultMeta({ record, existing, kind, policy }, _options = {}) {
124
128
  return policy.parseMeta({ kind, meta: { ...existing?.meta, credentialType: "custom",
125
129
  worksFor: [...(record.worksFor ?? existing?.meta.worksFor ?? [])],
@@ -55,6 +55,25 @@ async function normalKeyCard({ ctx, options, deps, host, saveNew }) {
55
55
  await admit({ deps, host, principalId: ctx.principal.id });
56
56
  return deps.projectKeys ? deps.projectKeys.savedResult({ result }) : result;
57
57
  }
58
+ /** The held key-picker card: selectable keys, locked keys as details, and an Enter a new key option. */
59
+ function keyPickerSurface({ host, uri, exchangeId, site, rows, available }, _options = {}) {
60
+ const { messages } = host;
61
+ const { toolId } = host.vocabulary;
62
+ return host.protocol.buildFormSurface({ uri,
63
+ title: messages.cardTitle, details: [{ label: messages.siteLabel, value: site?.name ?? messages.siteFallback }, ...lockedDetails({ rows, host })],
64
+ // A site key is added to Shared Keys on approval; the host's description says so, the owner is approving it.
65
+ description: available.length ? messages.cardDescription : messages.emptyCardDescription,
66
+ fields: [{ kind: 'enum', name: 'credentialId', label: messages.fieldLabel, required: true, placeholder: messages.fieldPlaceholder,
67
+ options: [...available.map(row => ({ value: row.keyId, label: row.name })), { value: host.vocabulary.newKeyValue, label: messages.newKeyLabel }] }],
68
+ // Keys and OAuth accounts stay in the owner store; shared OAuth keeps its original sign-in account and client.
69
+ // The label fits both a saved key and Enter a new key, which goes on to the normal key card.
70
+ // Start compact; Jini's shared bridge fits the body on load and content changes.
71
+ preferredFrameSize: ['100%', '1px'],
72
+ submitLabel: messages.submitLabel, toolName: toolId,
73
+ baseParams: { [SURFACE_EXCHANGE_ID_PARAM]: exchangeId },
74
+ cancel: { label: messages.cancelLabel, toolName: toolId, params: { [SURFACE_EXCHANGE_ID_PARAM]: exchangeId, [SURFACE_DISMISSED_PARAM]: true } },
75
+ });
76
+ }
58
77
  /** One human card selects and approves a CMS site grant. Jini owns actor binding, expiry and replay
59
78
  * protection. The site is captured by the project-keys port at host composition, never by submitted input.
60
79
  * @returns Only the approved reference, or a cancellation result; no owner inventory reaches chat.
@@ -85,23 +104,9 @@ export function createCredentialCopyRegistrations({ deps, surfaces, host }, { sa
85
104
  if (ctx.signal.aborted)
86
105
  abort();
87
106
  try {
88
- const { messages } = host;
89
107
  const available = rows.filter(row => !row.locked);
90
108
  const result = await host.protocol.askThenReport({ exchange,
91
- confirmationEmission: { channel: 'mcp-ui', payload: { resource: host.protocol.buildFormSurface({ uri,
92
- title: messages.cardTitle, details: [{ label: messages.siteLabel, value: projectKeys.site?.name ?? messages.siteFallback }, ...lockedDetails({ rows, host })],
93
- // A site key is added to Shared Keys on approval; the host's description says so, the owner is approving it.
94
- description: available.length ? messages.cardDescription : messages.emptyCardDescription,
95
- fields: [{ kind: 'enum', name: 'credentialId', label: messages.fieldLabel, required: true, placeholder: messages.fieldPlaceholder,
96
- options: [...available.map(row => ({ value: row.keyId, label: row.name })), { value: host.vocabulary.newKeyValue, label: messages.newKeyLabel }] }],
97
- // Keys and OAuth accounts stay in the owner store; shared OAuth keeps its original sign-in account and client.
98
- // The label fits both a saved key and Enter a new key, which goes on to the normal key card.
99
- // Start compact; Jini's shared bridge fits the body on load and content changes.
100
- preferredFrameSize: ['100%', '1px'],
101
- submitLabel: messages.submitLabel, toolName: toolId,
102
- baseParams: { [SURFACE_EXCHANGE_ID_PARAM]: exchange.id },
103
- cancel: { label: messages.cancelLabel, toolName: toolId, params: { [SURFACE_EXCHANGE_ID_PARAM]: exchange.id, [SURFACE_DISMISSED_PARAM]: true } },
104
- }) } },
109
+ confirmationEmission: { channel: 'mcp-ui', payload: { resource: keyPickerSurface({ host, uri, exchangeId: exchange.id, site: projectKeys.site, rows, available }) } },
105
110
  handle: async (answer) => {
106
111
  if (answer.status !== 'received' || ctx.signal.aborted)
107
112
  return { result: declined({ reason: 'interrupted', host }) };