@jini-ai/integrations 0.4.2 → 0.6.10
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/CHANGELOG.md +99 -1
- package/README.md +1 -0
- package/dist/api-connections/access-token.d.ts +9 -0
- package/dist/api-connections/access-token.js +92 -0
- package/dist/api-connections/account-actions.d.ts +40 -0
- package/dist/api-connections/account-actions.js +110 -0
- package/dist/api-connections/attempt-state.d.ts +28 -0
- package/dist/api-connections/attempt-state.js +73 -0
- package/dist/api-connections/authorization.d.ts +45 -0
- package/dist/api-connections/authorization.js +120 -0
- package/dist/api-connections/deps.d.ts +41 -0
- package/dist/api-connections/deps.js +13 -0
- package/dist/api-connections/descriptor.d.ts +6 -0
- package/dist/api-connections/descriptor.js +111 -0
- package/dist/api-connections/errors.d.ts +23 -0
- package/dist/api-connections/errors.js +24 -0
- package/dist/api-connections/finish-authorization.d.ts +24 -0
- package/dist/api-connections/finish-authorization.js +117 -0
- package/dist/api-connections/index.d.ts +18 -0
- package/dist/api-connections/index.js +10 -0
- package/dist/api-connections/install-credential.d.ts +19 -0
- package/dist/api-connections/install-credential.js +12 -0
- package/dist/api-connections/keys.d.ts +27 -0
- package/dist/api-connections/keys.js +22 -0
- package/dist/api-connections/ports.d.ts +73 -0
- package/dist/api-connections/ports.js +2 -0
- package/dist/api-connections/records.d.ts +27 -0
- package/dist/api-connections/records.js +52 -0
- package/dist/api-connections/request-checks.d.ts +18 -0
- package/dist/api-connections/request-checks.js +67 -0
- package/dist/api-connections/service.d.ts +25 -0
- package/dist/api-connections/service.js +26 -0
- package/dist/api-connections/status.d.ts +28 -0
- package/dist/api-connections/status.js +36 -0
- package/dist/api-connections/token-store/errors.d.ts +20 -0
- package/dist/api-connections/token-store/errors.js +38 -0
- package/dist/api-connections/token-store/index.d.ts +6 -0
- package/dist/api-connections/token-store/index.js +6 -0
- package/dist/api-connections/token-store/record.d.ts +69 -0
- package/dist/api-connections/token-store/record.js +97 -0
- package/dist/api-connections/token-store/vault-token-store.d.ts +26 -0
- package/dist/api-connections/token-store/vault-token-store.js +215 -0
- package/dist/api-connections/types.d.ts +101 -0
- package/dist/api-connections/types.js +9 -0
- package/dist/credentialed-http/auth-schemes.js +8 -4
- package/dist/credentialed-http/credentialed-request.d.ts +4 -0
- package/dist/credentialed-http/credentialed-request.js +61 -77
- package/dist/credentialed-http/response-redaction.d.ts +15 -0
- package/dist/credentialed-http/response-redaction.js +82 -0
- package/dist/media-providers/catalog.d.ts +3 -1
- package/dist/media-providers/catalog.js +3 -1
- package/dist/media-providers/dispatch/async-operation-store.d.ts +31 -0
- package/dist/media-providers/dispatch/async-operation-store.js +75 -37
- package/dist/media-providers/dispatch/builtin-vendors.d.ts +1 -1
- package/dist/media-providers/dispatch/context.js +10 -2
- package/dist/media-providers/dispatch/engine.d.ts +6 -3
- package/dist/media-providers/dispatch/engine.js +99 -109
- package/dist/media-providers/dispatch/index.d.ts +4 -2
- package/dist/media-providers/dispatch/index.js +3 -1
- package/dist/media-providers/dispatch/media-provider-registry.d.ts +62 -0
- package/dist/media-providers/dispatch/media-provider-registry.js +141 -0
- package/dist/media-providers/dispatch/node.d.ts +13 -0
- package/dist/media-providers/dispatch/node.js +24 -0
- package/dist/media-providers/dispatch/openai-compatible.d.ts +1 -1
- package/dist/media-providers/dispatch/openai-compatible.js +90 -87
- package/dist/media-providers/dispatch/operation-runtime.js +116 -89
- package/dist/media-providers/dispatch/outbound.d.ts +8 -4
- package/dist/media-providers/dispatch/outbound.js +27 -26
- package/dist/media-providers/dispatch/providers/aihubmix.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/aihubmix.js +61 -56
- package/dist/media-providers/dispatch/providers/custom-image.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/elevenlabs.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/fishaudio.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/grok.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/imagerouter-video-async.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/imagerouter-video-async.js +53 -49
- package/dist/media-providers/dispatch/providers/imagerouter.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/imagerouter.js +11 -24
- package/dist/media-providers/dispatch/providers/minimax.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/nanobanana.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/nanobanana.js +22 -30
- package/dist/media-providers/dispatch/providers/openai.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/openai.js +51 -47
- package/dist/media-providers/dispatch/providers/openrouter.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/openrouter.js +52 -37
- package/dist/media-providers/dispatch/providers/senseaudio.d.ts +1 -1
- package/dist/media-providers/dispatch/providers/senseaudio.js +47 -28
- package/dist/media-providers/dispatch/providers/volcengine.d.ts +1 -1
- package/dist/media-providers/dispatch/response-parsers.js +37 -21
- package/dist/media-providers/dispatch/sqlite-async-operation-store.js +9 -29
- package/dist/media-providers/dispatch/ssrf-guard.d.ts +3 -2
- package/dist/media-providers/dispatch/ssrf-guard.js +6 -5
- package/dist/media-providers/dispatch/types.d.ts +76 -2
- package/dist/media-providers/dispatch/vendor-adapter.d.ts +2 -43
- package/dist/media-providers/dispatch/vendor-adapter.js +2 -2
- package/dist/media-providers/dispatch/vendor-registry-core.d.ts +24 -0
- package/dist/media-providers/dispatch/vendor-registry-core.js +34 -0
- package/dist/media-providers/dispatch/vendor-registry.d.ts +10 -36
- package/dist/media-providers/dispatch/vendor-registry.js +14 -42
- package/dist/media-providers/policy.js +25 -17
- package/dist/media-providers/providers.d.ts +5 -0
- package/dist/media-providers/providers.js +2 -0
- package/dist/media-providers/sqlite-task-store.js +12 -80
- package/dist/media-providers/staging.js +77 -58
- package/dist/media-providers/task-lifecycle.d.ts +33 -0
- package/dist/media-providers/task-lifecycle.js +124 -0
- package/dist/media-providers/task-store.js +8 -86
- package/dist/media-providers/ui-defaults.d.ts +10 -0
- package/dist/media-providers/ui-defaults.js +167 -0
- package/dist/media-providers/video-request.js +112 -90
- package/dist/saved-requests/definition.d.ts +17 -0
- package/dist/saved-requests/definition.js +84 -0
- package/dist/saved-requests/execute.d.ts +17 -0
- package/dist/saved-requests/execute.js +95 -0
- package/dist/saved-requests/index.d.ts +6 -0
- package/dist/saved-requests/index.js +4 -0
- package/dist/saved-requests/projection.d.ts +9 -0
- package/dist/saved-requests/projection.js +48 -0
- package/dist/saved-requests/schema.d.ts +7 -0
- package/dist/saved-requests/schema.js +73 -0
- package/dist/saved-requests/types.d.ts +58 -0
- package/dist/saved-requests/types.js +2 -0
- package/dist/saved-requests/validation.d.ts +46 -0
- package/dist/saved-requests/validation.js +66 -0
- package/dist/webhooks/delivery.d.ts +14 -0
- package/dist/webhooks/delivery.js +41 -10
- package/dist/webhooks/index.d.ts +1 -0
- package/dist/webhooks/index.js +1 -0
- package/dist/webhooks/ports.d.ts +23 -0
- package/dist/webhooks/worker.d.ts +83 -0
- package/dist/webhooks/worker.js +105 -0
- package/package.json +46 -9
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,104 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.6.10
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 39b3f97: Name the update operation when refusing edits to a disabled (deleted) webhook subscription.
|
|
8
|
+
- 9b30143: Add `@jini-ai/integrations/saved-requests`: a declarative fixed-target HTTPS interpreter
|
|
9
|
+
with closed bounded input schemas, query/JSON-body value bindings, host-resolved credential
|
|
10
|
+
IDs and revision/origin binding, and typed positive output selection marked as untrusted.
|
|
11
|
+
Reuse credentialed HTTP authentication, redaction and audit over platform guarded egress
|
|
12
|
+
with no redirects, private-address denial, 64 KiB response/decompression caps and a 10s
|
|
13
|
+
deadline. Requires the existing optional platform and JSON-schema peers for this subpath.
|
|
14
|
+
|
|
15
|
+
Add the opt-in `makeCredentialedRequest` option `responseFormat: "json"` for decoded JSON
|
|
16
|
+
secret redaction, including refusal of credential-bearing keys/numbers and incomplete JSON.
|
|
17
|
+
|
|
18
|
+
- dc6efe5: Composio and the media-provider gateway collapse from two sibling packages under
|
|
19
|
+
`packages/integrations/` into subpaths of one package: `@jini-ai/integrations/composio` and
|
|
20
|
+
`@jini-ai/integrations/media-providers`. An npm package name allows only one slash, so the literal
|
|
21
|
+
import paths the repo owner wants require exactly this shape — one package with two subpath
|
|
22
|
+
exports, not two packages grouped under a shared directory.
|
|
23
|
+
|
|
24
|
+
This closes out two moves that happened earlier the same day. Composio was folded into
|
|
25
|
+
`@jini-ai/admin` as `./server` on 2026-08-01, then un-folded back into its own package under its
|
|
26
|
+
original published name, `@jini-ai/composio` (see the now-superseded
|
|
27
|
+
`composio-un-retirement.md`) — that un-retirement was never itself published, so no registry
|
|
28
|
+
version exists under that name beyond the pre-fold `0.2.1`. `@jini-ai/media` was separately renamed
|
|
29
|
+
and relocated to `@jini-ai/integrations-media-providers` (see the now-superseded
|
|
30
|
+
`media-providers-rename.md`); that rename was likewise never published — its own text notes the
|
|
31
|
+
version stays at `0.1.2` on disk pending a real release. Both collapse directly into this package's
|
|
32
|
+
two subpaths without ever taking an independent consumer-facing release under either intermediate
|
|
33
|
+
name.
|
|
34
|
+
|
|
35
|
+
**Breaking: `better-sqlite3` becomes an optional peer dependency of `./media-providers`, not a
|
|
36
|
+
regular dependency.** The concern that originally kept these as two separate packages — a
|
|
37
|
+
composio-only consumer being forced to install `better-sqlite3`, a native compiled addon — no
|
|
38
|
+
longer applies once both integrations share one package, because `better-sqlite3` is only ever
|
|
39
|
+
reached through a dynamic `await import('better-sqlite3')` inside `createSqliteMediaTaskStore`;
|
|
40
|
+
every other `./media-providers` export (the dispatch engine, capability registry, in-memory task
|
|
41
|
+
store, `renderStub`) never touches it. A consumer who calls `createSqliteMediaTaskStore` must now
|
|
42
|
+
`npm install better-sqlite3` themselves; everyone else installs nothing extra. This mirrors
|
|
43
|
+
`@jini-ai/admin`'s `react`/`react-dom` optional-peer convention.
|
|
44
|
+
|
|
45
|
+
No production logic changed — every file moved as-is from
|
|
46
|
+
`packages/integrations/{composio,media-providers}/src/**` into
|
|
47
|
+
`packages/integrations/src/{composio,media-providers}/**`. `examples/reference-web`, the one real
|
|
48
|
+
consumer of `./media-providers` in this workspace, is updated to the new import specifier.
|
|
49
|
+
|
|
50
|
+
**The standalone published names `@jini-ai/media` (`0.1.2`) and `@jini-ai/composio`
|
|
51
|
+
(`0.1.0`, `0.2.0`, `0.2.1`) are retired for good** — neither is versioned forward under its own
|
|
52
|
+
identity again. `@jini-ai/composio`'s deprecation was already flagged as a release
|
|
53
|
+
follow-up in `fold-composio-into-admin.md` (from the 2026-08-01 fold) and, as far as this workspace
|
|
54
|
+
shows, never acted on; it is restated here since it is still outstanding. `@jini-ai/media`'s
|
|
55
|
+
deprecation was not previously flagged anywhere. Whoever runs the next release should run both:
|
|
56
|
+
|
|
57
|
+
```
|
|
58
|
+
npm deprecate @jini-ai/media "Renamed and merged into @jini-ai/integrations; import from '@jini-ai/integrations/media-providers' instead."
|
|
59
|
+
npm deprecate @jini-ai/composio "Merged into @jini-ai/integrations; import from '@jini-ai/integrations/composio' instead."
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
- dc6efe5: Add `@jini-ai/integrations/media-providers/catalog` — a browser-safe entry exporting only the
|
|
63
|
+
vendor catalogue (`providers.ts`) and its types (`types.ts`).
|
|
64
|
+
|
|
65
|
+
The existing `./media-providers` entry is `jini.runtime: "node"` and its barrel statically pulls in
|
|
66
|
+
`node:crypto`/`node:fs`/`node:path` (`staging.ts`), `node:dns` (`dispatch/ssrf-guard.ts`), and
|
|
67
|
+
`undici` (`dispatch/providers/openai.ts`). A browser consumer that only needs the provider list to
|
|
68
|
+
render a credentials screen — Tovu's admin SPA is the first — previously had no way to get it
|
|
69
|
+
without dragging the whole dispatch engine into its bundle.
|
|
70
|
+
|
|
71
|
+
`providers.ts` imports only types from `types.ts`, and `types.ts` imports nothing, so the pair is
|
|
72
|
+
genuinely dependency-free; the new entry is marked `"universal"` in `jini.entries`. Verified by
|
|
73
|
+
importing the built subpath from a directory containing nothing but this package's `dist/` and
|
|
74
|
+
`package.json` — 11 exports, 25 vendors, no dispatch symbols reachable — while
|
|
75
|
+
`./media-providers` fails with `ERR_MODULE_NOT_FOUND` on `@jini-ai/core` in the same environment.
|
|
76
|
+
|
|
77
|
+
`__tests__/catalog.test.ts` walks the transitive source graph and asserts it contains exactly
|
|
78
|
+
`catalog.ts`/`providers.ts`/`types.ts` with zero bare import specifiers, so re-exporting anything
|
|
79
|
+
node-bound from this entry fails a test rather than a downstream bundle.
|
|
80
|
+
|
|
81
|
+
Additive only — no existing entry, export, or type changed.
|
|
82
|
+
|
|
83
|
+
- ea8d883: Refuse subscription updates after soft deletion, before target validation or repository writes.
|
|
84
|
+
- Updated dependencies [22f0619]
|
|
85
|
+
- Updated dependencies [82ed2d3]
|
|
86
|
+
- Updated dependencies [5a3de86]
|
|
87
|
+
- @jini-ai/core@0.6.10
|
|
88
|
+
|
|
89
|
+
## 0.4.3 — 2026-10-22
|
|
90
|
+
|
|
91
|
+
- 2026-10-22: Webhook delivery deadlines, leases and fencing; media-provider model-id collision refusal; provider contributions.
|
|
92
|
+
|
|
93
|
+
### Minor Changes
|
|
94
|
+
|
|
95
|
+
- media-providers: vendors are one-unit provider contributions (`{ provider, models, adapters }`) on the
|
|
96
|
+
shared `@jini-ai/core/provider-registry` (contract `media`). `createMediaProviderRegistry()` (built-ins
|
|
97
|
+
are the default contribution set; plugins `contribute`, refused not thrown) implements both
|
|
98
|
+
`VendorAdapterLookup` and the new `MediaModelCatalog`. `createMediaDispatchEngine` takes an optional
|
|
99
|
+
`catalog`, so plugin models validate; omitted, behaviour is unchanged. Registry keys map `-` to `_`;
|
|
100
|
+
public provider ids are unchanged.
|
|
101
|
+
|
|
3
102
|
## 0.4.1
|
|
4
103
|
|
|
5
104
|
### Patch Changes
|
|
@@ -48,7 +147,6 @@
|
|
|
48
147
|
- Composio retains 2000ms timeout, 10ms polling and no age/dead-owner stealing. Shared locking adds owned-create cleanup and inode/device snapshot checks.
|
|
49
148
|
- Native fetch ABIs and media egress paths remain unchanged; provider-host policy retains existing loopback allowance.
|
|
50
149
|
|
|
51
|
-
|
|
52
150
|
## Unreleased
|
|
53
151
|
|
|
54
152
|
- Add `./credentialed-http`: resolver, HTTP, scheme-registry and audit ports; origin binding,
|
package/README.md
CHANGED
|
@@ -8,6 +8,7 @@ exports. Import the capability you need; each entry owns its dependencies and ru
|
|
|
8
8
|
| `./media-providers` | Node | Image/video/audio gateway, policy, staging and task stores |
|
|
9
9
|
| `./media-providers/catalog` | Universal | Browser-safe provider/model catalog |
|
|
10
10
|
| `./credentialed-http` | Node | Credential-origin binding, authentication, redacted responses and audit ports |
|
|
11
|
+
| `./saved-requests` | Node | Fixed-target declarative requests, bounded schemas and typed public projections |
|
|
11
12
|
| `./webhooks` | Node | Subscriptions, delivery/retries and signing through host ports |
|
|
12
13
|
|
|
13
14
|
## No root `.` export
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { ApiConnectionServiceDeps } from './deps.js';
|
|
2
|
+
import { type OwnedRecordArgs } from './records.js';
|
|
3
|
+
export interface ApiConnectionAccessTokens {
|
|
4
|
+
getAccessToken(requiredArgs: OwnedRecordArgs, optionalArgs?: {
|
|
5
|
+
readonly expectedAccountId?: string;
|
|
6
|
+
}): Promise<string>;
|
|
7
|
+
}
|
|
8
|
+
export declare function createApiConnectionAccessTokens(deps: ApiConnectionServiceDeps): ApiConnectionAccessTokens;
|
|
9
|
+
//# sourceMappingURL=access-token.d.ts.map
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Serves access tokens for a connection, refreshing through the OAuth core's refresher.
|
|
3
|
+
*
|
|
4
|
+
* Exists so plugin tool and delivery code never touch refresh tokens: they ask for an access
|
|
5
|
+
* token by `connectionRef` immediately before an HTTP call. Only `connected` records are served,
|
|
6
|
+
* an optional frozen account id stops a binding from silently following an account switch (checked
|
|
7
|
+
* again after the token is read, so a switch landing in between cannot leak through), and a
|
|
8
|
+
* rejected refresh or unreadable credential moves the record to `reconnect-required`. Unreadable
|
|
9
|
+
* credentials are preserved, and their internal store errors become a clear reconnect instruction.
|
|
10
|
+
*/
|
|
11
|
+
import { createTokenRefresher, OAuthError, refreshAccessToken } from '@jini-ai/oauth';
|
|
12
|
+
import { ApiConnectionError } from './errors.js';
|
|
13
|
+
import { loadOwnedRecord, writeRecord } from './records.js';
|
|
14
|
+
import { isUnreadableTokenRecord } from './token-store/errors.js';
|
|
15
|
+
const REFUSALS = {
|
|
16
|
+
'reconnect-required': { code: 'reconnect-required', message: 'This connection needs to be reconnected. Reconnect the account in the connection settings.' },
|
|
17
|
+
'revocation-pending': { code: 'revocation-pending', message: 'This connection was disconnected. Finish disconnecting or connect again.' },
|
|
18
|
+
disconnected: { code: 'not-connected', message: 'This connection is not connected. Connect the account first.' },
|
|
19
|
+
};
|
|
20
|
+
function assertServable(record, expectedAccountId) {
|
|
21
|
+
if (record.status !== 'connected')
|
|
22
|
+
throw new ApiConnectionError(REFUSALS[record.status]);
|
|
23
|
+
if (expectedAccountId !== undefined && record.account?.accountId !== expectedAccountId) {
|
|
24
|
+
throw new ApiConnectionError({ code: 'account-changed',
|
|
25
|
+
message: 'This connection now uses a different account than this task was set up with. Review the task and reassign it.' });
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Status write after a terminal credential failure; only a still-connected record is downgraded.
|
|
30
|
+
* When a failed read names a generation, a newer sign-in is left alone. Revision CAS also
|
|
31
|
+
* protects changes landing after this read. Tokens are preserved; storage failures propagate.
|
|
32
|
+
* @complexity One record read and at most one CAS write.
|
|
33
|
+
*/
|
|
34
|
+
async function markReconnectRequired(deps, key, options = {}) {
|
|
35
|
+
const record = await deps.records.read({ key });
|
|
36
|
+
if (record?.status !== 'connected')
|
|
37
|
+
return;
|
|
38
|
+
if (options.expectedGeneration !== undefined && record.generation !== options.expectedGeneration)
|
|
39
|
+
return;
|
|
40
|
+
await writeRecord(deps, record, { status: 'reconnect-required' });
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The token store reads the live generation, so a confirmed switch, disconnect or reconnect that
|
|
44
|
+
* landed between the record check and the token read could hand over another credential: refuse
|
|
45
|
+
* unless the record still serves the same generation. A retry reads the new state consistently.
|
|
46
|
+
*/
|
|
47
|
+
async function assertUnchangedSince(deps, requiredArgs) {
|
|
48
|
+
const current = await loadOwnedRecord(deps, requiredArgs);
|
|
49
|
+
assertServable(current, requiredArgs.expectedAccountId);
|
|
50
|
+
if (current.generation !== requiredArgs.checked.generation) {
|
|
51
|
+
throw new ApiConnectionError({ code: 'storage-conflict',
|
|
52
|
+
message: 'This connection changed while the request was running. Reload its status and try again.' });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function refreshPort(deps) {
|
|
56
|
+
const { tokens } = deps;
|
|
57
|
+
return {
|
|
58
|
+
load: args => tokens.load(args),
|
|
59
|
+
persist: args => tokens.persist(args),
|
|
60
|
+
async markNeedsReauth(args) {
|
|
61
|
+
await tokens.markNeedsReauth(args);
|
|
62
|
+
await markReconnectRequired(deps, args.key);
|
|
63
|
+
},
|
|
64
|
+
...(tokens.tryAcquireRefreshLease ? { tryAcquireRefreshLease: tokens.tryAcquireRefreshLease.bind(tokens) } : {}),
|
|
65
|
+
...(tokens.releaseRefreshLease ? { releaseRefreshLease: tokens.releaseRefreshLease.bind(tokens) } : {}),
|
|
66
|
+
refresh: ({ refreshToken }) => refreshAccessToken({ fetchFn: deps.fetchFn, guard: deps.guard, clock: deps.clock,
|
|
67
|
+
tokenEndpoint: deps.descriptor.tokenEndpoint, client: deps.client, refreshToken }),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
export function createApiConnectionAccessTokens(deps) {
|
|
71
|
+
const refresher = createTokenRefresher({ clock: deps.clock, sleep: deps.sleep, port: refreshPort(deps) });
|
|
72
|
+
return {
|
|
73
|
+
async getAccessToken(requiredArgs, optionalArgs = {}) {
|
|
74
|
+
const { expectedAccountId } = optionalArgs;
|
|
75
|
+
const record = await loadOwnedRecord(deps, requiredArgs);
|
|
76
|
+
assertServable(record, expectedAccountId);
|
|
77
|
+
const accessToken = await refresher.getAccessToken({ key: record.key }).catch(async (error) => {
|
|
78
|
+
if (isUnreadableTokenRecord(error)) {
|
|
79
|
+
await markReconnectRequired(deps, record.key, { expectedGeneration: record.generation });
|
|
80
|
+
throw new ApiConnectionError(REFUSALS['reconnect-required'], { cause: error });
|
|
81
|
+
}
|
|
82
|
+
if (error instanceof OAuthError && error.code === 'OAUTH_INVALID_GRANT') {
|
|
83
|
+
throw new ApiConnectionError(REFUSALS['reconnect-required'], { cause: error });
|
|
84
|
+
}
|
|
85
|
+
throw error;
|
|
86
|
+
});
|
|
87
|
+
await assertUnchangedSince(deps, { ...requiredArgs, checked: record, expectedAccountId });
|
|
88
|
+
return accessToken;
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
//# sourceMappingURL=access-token.js.map
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Account actions after sign-in: confirm or cancel a staged switch, and disconnect.
|
|
3
|
+
*
|
|
4
|
+
* Exists so the rules owners care about live in one place: a switch only takes effect on an
|
|
5
|
+
* explicit confirm by the actor who staged it, against the generation it was staged on; a
|
|
6
|
+
* disconnect stops use first, then asks the plugin to revoke remotely, clears local tokens only
|
|
7
|
+
* after the provider confirmed, and otherwise stays `revocation-pending` with the disabled
|
|
8
|
+
* credential kept for a retry. Remote success is never reported unless the hook returned.
|
|
9
|
+
*/
|
|
10
|
+
import type { ApiConnectionServiceDeps } from './deps.js';
|
|
11
|
+
import { type OwnedRecordArgs } from './records.js';
|
|
12
|
+
import { type ApiConnectionStatusView } from './status.js';
|
|
13
|
+
/**
|
|
14
|
+
* `not-needed` when no credential existed locally, so nothing could be revoked. `pending` with
|
|
15
|
+
* status `revocation-pending` means the disabled credential is kept and disconnecting again
|
|
16
|
+
* retries; `pending` with status `disconnected` means the stored credential could not be read
|
|
17
|
+
* (for example the host changed its OAuth client), so it was removed locally and the person has
|
|
18
|
+
* to remove the access on the provider's account page.
|
|
19
|
+
*/
|
|
20
|
+
export type ApiConnectionRemoteRevocation = 'confirmed' | 'pending' | 'not-needed';
|
|
21
|
+
export interface ApiConnectionDisconnectResult extends ApiConnectionStatusView {
|
|
22
|
+
readonly remoteRevocation: ApiConnectionRemoteRevocation;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* A confirmed switch never revokes the previous account's grant at the provider: revoking it could
|
|
26
|
+
* cut off the same account connected elsewhere through the same client. Hosts say so and link the
|
|
27
|
+
* provider's account-access page; the local copy of its tokens is gone.
|
|
28
|
+
*/
|
|
29
|
+
export type ApiConnectionSwitchResult = ApiConnectionStatusView;
|
|
30
|
+
export declare function confirmSwitchAccount(deps: ApiConnectionServiceDeps, requiredArgs: OwnedRecordArgs & {
|
|
31
|
+
readonly actorId: string;
|
|
32
|
+
}): Promise<ApiConnectionSwitchResult>;
|
|
33
|
+
/**
|
|
34
|
+
* Drop a staged switch, revoking its tokens because the person consented to them. When the
|
|
35
|
+
* provider does not confirm, the switch stays staged (still confirmable) and cancelling again retries.
|
|
36
|
+
*/
|
|
37
|
+
export declare function cancelSwitchAccount(deps: ApiConnectionServiceDeps, requiredArgs: OwnedRecordArgs): Promise<ApiConnectionDisconnectResult>;
|
|
38
|
+
/** Disconnect and revoke the live and any staged credential; call again to retry a `pending` revocation. */
|
|
39
|
+
export declare function disconnectApiConnection(deps: ApiConnectionServiceDeps, requiredArgs: OwnedRecordArgs): Promise<ApiConnectionDisconnectResult>;
|
|
40
|
+
//# sourceMappingURL=account-actions.d.ts.map
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { ApiConnectionError } from './errors.js';
|
|
2
|
+
import { installCredential } from './install-credential.js';
|
|
3
|
+
import { isUnreadableTokenRecord } from './token-store/errors.js';
|
|
4
|
+
import { stagedTokenKey } from './keys.js';
|
|
5
|
+
import { loadOwnedRecord, writeRecord } from './records.js';
|
|
6
|
+
import { toStatusView } from './status.js';
|
|
7
|
+
/** Classifications a revoke hook may put on its error's `code`; anything else is `unclassified`. */
|
|
8
|
+
const HOOK_FAILURE_CODES = new Set(['provider-unreachable', 'provider-refused']);
|
|
9
|
+
/** Read only the hook's `code`, and only when it is a known classification: its message may echo provider bodies. */
|
|
10
|
+
function hookFailureOf(error) {
|
|
11
|
+
// A hook may throw anything, `undefined` included.
|
|
12
|
+
const code = error?.code;
|
|
13
|
+
return HOOK_FAILURE_CODES.has(code) ? code : 'unclassified';
|
|
14
|
+
}
|
|
15
|
+
function switchNotStaged() {
|
|
16
|
+
return new ApiConnectionError({ code: 'switch-not-staged',
|
|
17
|
+
message: 'There is no account switch waiting for your confirmation, or it expired. Cancel the switch and start it again.' });
|
|
18
|
+
}
|
|
19
|
+
function stagedSwitchUsable(record, actorId, nowMs) {
|
|
20
|
+
const staged = record.staged;
|
|
21
|
+
return staged !== null && staged.actorId === actorId && staged.generation === record.generation
|
|
22
|
+
&& Date.parse(staged.expiresAt) > nowMs;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Revoke the credential stored under `key` through the plugin hook and delete it only when the
|
|
26
|
+
* hook returned. The read ignores the generation fence: a disconnect has already disabled the
|
|
27
|
+
* credential, and these tokens go to the revoke hook only.
|
|
28
|
+
*/
|
|
29
|
+
async function revokeStoredCredential(deps, key) {
|
|
30
|
+
const tokens = await deps.tokens.loadForRevocation({ key }).catch((error) => {
|
|
31
|
+
if (isUnreadableTokenRecord(error))
|
|
32
|
+
return 'unreadable';
|
|
33
|
+
throw error;
|
|
34
|
+
});
|
|
35
|
+
// Nothing can ever revoke with an unreadable row; keeping it would block every later sign-in.
|
|
36
|
+
if (tokens === 'unreadable') {
|
|
37
|
+
await deps.tokens.delete({ key });
|
|
38
|
+
return { outcome: 'abandoned', failure: 'credential-unreadable' };
|
|
39
|
+
}
|
|
40
|
+
if (tokens === null)
|
|
41
|
+
return { outcome: 'not-needed', failure: null };
|
|
42
|
+
try {
|
|
43
|
+
await deps.hooks.revoke({ token: tokens.refreshToken ?? tokens.accessToken });
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
// The hook's error may echo provider bodies; the outcome and a fixed code, not the detail, is
|
|
47
|
+
// what callers and the record get. The credential stays (disabled) so a retry can still revoke.
|
|
48
|
+
return { outcome: 'pending', failure: hookFailureOf(error) };
|
|
49
|
+
}
|
|
50
|
+
await deps.tokens.delete({ key });
|
|
51
|
+
return { outcome: 'confirmed', failure: null };
|
|
52
|
+
}
|
|
53
|
+
/** One outcome for several credentials: any pending (or abandoned) wins, then any confirmed. */
|
|
54
|
+
function combineRevocations(outcomes) {
|
|
55
|
+
if (outcomes.includes('pending') || outcomes.includes('abandoned'))
|
|
56
|
+
return 'pending';
|
|
57
|
+
return outcomes.includes('confirmed') ? 'confirmed' : 'not-needed';
|
|
58
|
+
}
|
|
59
|
+
/** The first failure among several credentials (the live one is revoked first), or null. */
|
|
60
|
+
function firstFailure(results) {
|
|
61
|
+
return results.find(result => result.failure !== null)?.failure ?? null;
|
|
62
|
+
}
|
|
63
|
+
export async function confirmSwitchAccount(deps, requiredArgs) {
|
|
64
|
+
const record = await loadOwnedRecord(deps, requiredArgs);
|
|
65
|
+
if (!stagedSwitchUsable(record, requiredArgs.actorId, deps.clock.nowMs()))
|
|
66
|
+
throw switchNotStaged();
|
|
67
|
+
const stagedKey = stagedTokenKey({ key: record.key });
|
|
68
|
+
const tokens = await deps.tokens.load({ key: stagedKey });
|
|
69
|
+
if (tokens === null)
|
|
70
|
+
throw switchNotStaged();
|
|
71
|
+
const staged = record.staged;
|
|
72
|
+
const updated = await installCredential(deps, { current: record, tokens, account: staged.account, grantedScopes: staged.grantedScopes });
|
|
73
|
+
await deps.tokens.delete({ key: stagedKey });
|
|
74
|
+
return toStatusView(updated);
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Drop a staged switch, revoking its tokens because the person consented to them. When the
|
|
78
|
+
* provider does not confirm, the switch stays staged (still confirmable) and cancelling again retries.
|
|
79
|
+
*/
|
|
80
|
+
export async function cancelSwitchAccount(deps, requiredArgs) {
|
|
81
|
+
const record = await loadOwnedRecord(deps, requiredArgs);
|
|
82
|
+
// Without a staged record the slot can only hold a confirmed switch's copy of the live grant
|
|
83
|
+
// (or a credential a pending disconnect owns): revoking it here would cut off the live account.
|
|
84
|
+
if (record.staged === null)
|
|
85
|
+
return { ...toStatusView(record), remoteRevocation: 'not-needed' };
|
|
86
|
+
const result = await revokeStoredCredential(deps, stagedTokenKey({ key: record.key }));
|
|
87
|
+
const updated = await writeRecord(deps, record, result.outcome === 'pending'
|
|
88
|
+
? { revocationFailure: result.failure } : { staged: null, revocationFailure: result.failure });
|
|
89
|
+
return { ...toStatusView(updated), remoteRevocation: combineRevocations([result.outcome]) };
|
|
90
|
+
}
|
|
91
|
+
/** Disconnect and revoke the live and any staged credential; call again to retry a `pending` revocation. */
|
|
92
|
+
export async function disconnectApiConnection(deps, requiredArgs) {
|
|
93
|
+
const record = await loadOwnedRecord(deps, requiredArgs);
|
|
94
|
+
// Stop use before any network call: no token is served or refreshed once the generation moves.
|
|
95
|
+
const stopped = record.status === 'revocation-pending' ? record
|
|
96
|
+
: await writeRecord(deps, record, { status: 'revocation-pending', generation: record.generation + 1, staged: null });
|
|
97
|
+
const results = [
|
|
98
|
+
await revokeStoredCredential(deps, record.key),
|
|
99
|
+
await revokeStoredCredential(deps, stagedTokenKey({ key: record.key })),
|
|
100
|
+
];
|
|
101
|
+
const outcomes = results.map(result => result.outcome);
|
|
102
|
+
const remoteRevocation = combineRevocations(outcomes);
|
|
103
|
+
const revocationFailure = firstFailure(results);
|
|
104
|
+
// Only a kept credential can be retried; an abandoned one leaves nothing to wait for locally.
|
|
105
|
+
if (outcomes.includes('pending'))
|
|
106
|
+
return { ...toStatusView(await writeRecord(deps, stopped, { revocationFailure })), remoteRevocation };
|
|
107
|
+
const cleared = await writeRecord(deps, stopped, { status: 'disconnected', account: null, grantedScopes: [], revocationFailure });
|
|
108
|
+
return { ...toStatusView(cleared), remoteRevocation };
|
|
109
|
+
}
|
|
110
|
+
//# sourceMappingURL=account-actions.js.map
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { type SealedAuthorizationState } from '@jini-ai/oauth';
|
|
2
|
+
import type { ApiConnectionServiceDeps } from './deps.js';
|
|
3
|
+
import type { ApiConnectionAttempt } from './types.js';
|
|
4
|
+
/** Long enough for consent and multi-factor prompts; abandoned attempts die quickly. */
|
|
5
|
+
export declare const ATTEMPT_TTL_MS: number;
|
|
6
|
+
/** Same strength as `state`: the binding is what a forwarded authorization URL cannot carry along. */
|
|
7
|
+
export declare const BROWSER_BINDING_BYTES = 32;
|
|
8
|
+
/**
|
|
9
|
+
* The stored form of a browser binding, so a leaked attempt row cannot be replayed as a cookie.
|
|
10
|
+
* A host bug passing a non-string hashes as '', which no 32-byte binding ever matches.
|
|
11
|
+
*/
|
|
12
|
+
export declare function hashBrowserBinding(value: unknown): string;
|
|
13
|
+
type AttemptDraft = Omit<ApiConnectionAttempt, 'state' | 'codeVerifier' | 'redirectUri' | 'createdAt' | 'expiresAt'>;
|
|
14
|
+
type AttemptDeps = Pick<ApiConnectionServiceDeps, 'records' | 'clock' | 'randomBytesFn'>;
|
|
15
|
+
/** Seal side: store the attempt under fresh random state. */
|
|
16
|
+
export declare function attemptSealer(deps: AttemptDeps, requiredArgs: {
|
|
17
|
+
readonly draft: AttemptDraft;
|
|
18
|
+
}): SealedAuthorizationState;
|
|
19
|
+
/** Open side: consume first, then check binding, so a probe burns the state it guessed. */
|
|
20
|
+
export declare function attemptOpener(deps: AttemptDeps, requiredArgs: {
|
|
21
|
+
/** The binding the callback's browser carried; the core's `open` arguments have no slot for it. */
|
|
22
|
+
readonly browserBinding: string;
|
|
23
|
+
readonly onOpen: (requiredArgs: {
|
|
24
|
+
readonly attempt: ApiConnectionAttempt;
|
|
25
|
+
}) => void;
|
|
26
|
+
}): SealedAuthorizationState;
|
|
27
|
+
export {};
|
|
28
|
+
//# sourceMappingURL=attempt-state.d.ts.map
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Adapts the record store's attempts to the OAuth core's `SealedAuthorizationState` seam.
|
|
3
|
+
*
|
|
4
|
+
* Exists so `beginAuthorizationCode`/`completeAuthorizationCode` keep owning PKCE, redirect
|
|
5
|
+
* allowlisting, callback errors and the token exchange, while the attempt itself is a stored,
|
|
6
|
+
* expiring, single-use record bound to workspace, actor, plugin connection, callback URI,
|
|
7
|
+
* credential generation and the browser that started it. Every redemption failure is the core's
|
|
8
|
+
* indistinguishable invalid-state.
|
|
9
|
+
*/
|
|
10
|
+
import { createHash } from 'node:crypto';
|
|
11
|
+
import { invalidPendingAuthorizationState, PENDING_AUTHORIZATION_STATE_BYTES, generateOAuthState, secureEqualsForOwnerBinding } from '@jini-ai/oauth';
|
|
12
|
+
import { nowIso } from '@jini-ai/core/primitives';
|
|
13
|
+
/** Long enough for consent and multi-factor prompts; abandoned attempts die quickly. */
|
|
14
|
+
export const ATTEMPT_TTL_MS = 10 * 60 * 1000;
|
|
15
|
+
/** Same strength as `state`: the binding is what a forwarded authorization URL cannot carry along. */
|
|
16
|
+
export const BROWSER_BINDING_BYTES = 32;
|
|
17
|
+
/**
|
|
18
|
+
* The stored form of a browser binding, so a leaked attempt row cannot be replayed as a cookie.
|
|
19
|
+
* A host bug passing a non-string hashes as '', which no 32-byte binding ever matches.
|
|
20
|
+
*/
|
|
21
|
+
export function hashBrowserBinding(value) {
|
|
22
|
+
return createHash('sha256').update(typeof value === 'string' ? value : '').digest('base64url');
|
|
23
|
+
}
|
|
24
|
+
function toPending(attempt, providerId) {
|
|
25
|
+
return {
|
|
26
|
+
state: attempt.state, ownerKey: attempt.ownerKey, providerId, codeVerifier: attempt.codeVerifier,
|
|
27
|
+
redirectUri: attempt.redirectUri, scopes: attempt.requestedScopes, createdAt: attempt.createdAt, expiresAt: attempt.expiresAt,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
/** Each adapter serves one direction; reaching the other means the core changed its contract. */
|
|
31
|
+
async function refuseUnexpected() {
|
|
32
|
+
throw invalidPendingAuthorizationState({});
|
|
33
|
+
}
|
|
34
|
+
/** Seal side: store the attempt under fresh random state. */
|
|
35
|
+
export function attemptSealer(deps, requiredArgs) {
|
|
36
|
+
return {
|
|
37
|
+
async seal({ entry }) {
|
|
38
|
+
const createdAt = nowIso({ clock: deps.clock });
|
|
39
|
+
const attempt = {
|
|
40
|
+
...requiredArgs.draft, codeVerifier: entry.codeVerifier, redirectUri: entry.redirectUri, createdAt,
|
|
41
|
+
state: generateOAuthState({ randomBytesFn: deps.randomBytesFn }, { stateBytes: PENDING_AUTHORIZATION_STATE_BYTES }),
|
|
42
|
+
expiresAt: new Date(Date.parse(createdAt) + ATTEMPT_TTL_MS).toISOString(),
|
|
43
|
+
};
|
|
44
|
+
await deps.records.putAttempt({ attempt });
|
|
45
|
+
return toPending(attempt, entry.providerId);
|
|
46
|
+
},
|
|
47
|
+
open: refuseUnexpected,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
function matchesBinding(attempt, expected, nowMs) {
|
|
51
|
+
return Date.parse(attempt.expiresAt) > nowMs
|
|
52
|
+
&& secureEqualsForOwnerBinding({ a: attempt.ownerKey, b: expected.ownerKey })
|
|
53
|
+
// The owner key alone cannot bind a hosted callback: a cookie-less callback route can only learn
|
|
54
|
+
// the identities from the attempt itself. The browser binding is what the redirected browser carries.
|
|
55
|
+
&& secureEqualsForOwnerBinding({ a: attempt.browserBindingHash, b: hashBrowserBinding(expected.browserBinding) })
|
|
56
|
+
&& attempt.redirectUri === expected.redirectUri;
|
|
57
|
+
}
|
|
58
|
+
/** Open side: consume first, then check binding, so a probe burns the state it guessed. */
|
|
59
|
+
export function attemptOpener(deps, requiredArgs) {
|
|
60
|
+
const { browserBinding } = requiredArgs;
|
|
61
|
+
return {
|
|
62
|
+
seal: refuseUnexpected,
|
|
63
|
+
async open({ state, ownerKey, providerId, redirectUri }) {
|
|
64
|
+
const attempt = await deps.records.takeAttempt({ state });
|
|
65
|
+
if (attempt === null || !matchesBinding(attempt, { ownerKey, redirectUri, browserBinding }, deps.clock.nowMs())) {
|
|
66
|
+
throw invalidPendingAuthorizationState({});
|
|
67
|
+
}
|
|
68
|
+
requiredArgs.onOpen({ attempt });
|
|
69
|
+
return toPending(attempt, providerId);
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
//# sourceMappingURL=attempt-state.js.map
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { ApiConnectionServiceDeps } from './deps.js';
|
|
2
|
+
import { type CompletedAuthorization } from './finish-authorization.js';
|
|
3
|
+
import type { ApiConnectionIntent } from './types.js';
|
|
4
|
+
export interface StartApiConnectionResult {
|
|
5
|
+
/** Stable reference to this connection; the same value on every reconnect. */
|
|
6
|
+
readonly connectionRef: string;
|
|
7
|
+
readonly authorizationUrl: string;
|
|
8
|
+
/**
|
|
9
|
+
* Host-only: the callback's CSRF binding, for the host's own routing (e.g. arming a loopback
|
|
10
|
+
* receiver). Never hand it to plugin code or a frame; give them `attemptId` instead.
|
|
11
|
+
*/
|
|
12
|
+
readonly state: string;
|
|
13
|
+
/** Opaque, random id of this sign-in; `complete` returns the same id (e.g. to key callback fields). */
|
|
14
|
+
readonly attemptId: string;
|
|
15
|
+
/**
|
|
16
|
+
* Host-only: proof that a callback arrives in the browser that started this sign-in. Hand it to
|
|
17
|
+
* that browser (see the README's host contract) and pass it back to `complete`; never to plugin
|
|
18
|
+
* code, a frame, logs or the authorization URL. Only its hash is stored.
|
|
19
|
+
*/
|
|
20
|
+
readonly browserBinding: string;
|
|
21
|
+
readonly expiresAt: string;
|
|
22
|
+
}
|
|
23
|
+
export declare function startApiConnectionAuthorization(deps: ApiConnectionServiceDeps, requiredArgs: {
|
|
24
|
+
readonly workspaceId: string;
|
|
25
|
+
readonly actorId: string;
|
|
26
|
+
readonly intent: ApiConnectionIntent;
|
|
27
|
+
readonly scopeSetIds: readonly string[];
|
|
28
|
+
readonly redirectUri: string;
|
|
29
|
+
}, optionalArgs?: {
|
|
30
|
+
readonly startParams?: Readonly<Record<string, string>>;
|
|
31
|
+
}): Promise<StartApiConnectionResult>;
|
|
32
|
+
/**
|
|
33
|
+
* Redeem the callback. `redirectUri` is the exact callback URL this request arrived on and the
|
|
34
|
+
* identities are the host's authenticated session, never values read from the callback itself.
|
|
35
|
+
* `browserBinding` is what the callback's browser carried back (`''` when it carried none); a
|
|
36
|
+
* missing or different binding burns the attempt with the same `invalid-attempt`.
|
|
37
|
+
*/
|
|
38
|
+
export declare function completeApiConnectionAuthorization(deps: ApiConnectionServiceDeps, requiredArgs: {
|
|
39
|
+
readonly workspaceId: string;
|
|
40
|
+
readonly actorId: string;
|
|
41
|
+
readonly redirectUri: string;
|
|
42
|
+
readonly callbackParams: Readonly<Record<string, string>>;
|
|
43
|
+
readonly browserBinding: string;
|
|
44
|
+
}): Promise<CompletedAuthorization>;
|
|
45
|
+
//# sourceMappingURL=authorization.d.ts.map
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Starts and completes an API-connection sign-in (authorization code + PKCE S256).
|
|
3
|
+
*
|
|
4
|
+
* Exists to bind the OAuth core's browser grant to a plugin connection: start records an
|
|
5
|
+
* expiring single-use attempt bound to workspace, actor, plugin connection, requested scopes,
|
|
6
|
+
* callback URI, credential generation and the starting browser; complete redeems it exactly once,
|
|
7
|
+
* exchanges the code, and hands the token set to `finishAuthorization` for the grant, identity and
|
|
8
|
+
* commit checks.
|
|
9
|
+
*/
|
|
10
|
+
import { beginAuthorizationCode, completeAuthorizationCode, generateOAuthState, OAuthError } from '@jini-ai/oauth';
|
|
11
|
+
import { ApiConnectionError, invalidAttempt } from './errors.js';
|
|
12
|
+
import { attemptOpener, attemptSealer, BROWSER_BINDING_BYTES, hashBrowserBinding } from './attempt-state.js';
|
|
13
|
+
import { finishAuthorization, loadReadableTokens } from './finish-authorization.js';
|
|
14
|
+
import { deriveApiConnectionKey } from './keys.js';
|
|
15
|
+
import { assertId, checkCallbackParams, checkScopes, checkStartParams, pickBoundedFields, requestInvalid } from './request-checks.js';
|
|
16
|
+
/** Same encoding as `state`, half the entropy: it names an attempt, it does not guard one. */
|
|
17
|
+
const ATTEMPT_ID_BYTES = 16;
|
|
18
|
+
function providerFor(deps) {
|
|
19
|
+
const { descriptor } = deps;
|
|
20
|
+
return {
|
|
21
|
+
providerId: `${descriptor.pluginId}/${descriptor.connectionId}`, label: descriptor.label,
|
|
22
|
+
supportedGrants: ['authorization_code'], authorizationEndpoint: descriptor.authorizationEndpoint,
|
|
23
|
+
tokenEndpoint: descriptor.tokenEndpoint, defaultScopes: [], usesPkce: true, clientAuth: deps.client.authMethod,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
/** One canonical string per (workspace, actor, plugin connection); JSON keeps it injective. */
|
|
27
|
+
function ownerKeyFor(deps, requiredArgs) {
|
|
28
|
+
return JSON.stringify([requiredArgs.workspaceId, requiredArgs.actorId, deps.descriptor.pluginId, deps.descriptor.connectionId]);
|
|
29
|
+
}
|
|
30
|
+
function assertStartAllowed(record, intent) {
|
|
31
|
+
// The disabled credential is kept for a revocation retry; a new sign-in would orphan it.
|
|
32
|
+
if (record?.status === 'revocation-pending') {
|
|
33
|
+
throw new ApiConnectionError({ code: 'revocation-pending',
|
|
34
|
+
message: 'This connection is disconnected locally but remote revocation is still pending. Retry disconnecting first.' });
|
|
35
|
+
}
|
|
36
|
+
// A new sign-in would overwrite (switch) or orphan (connect) the staged credential without revoking it.
|
|
37
|
+
if (record != null && record.staged !== null) {
|
|
38
|
+
throw new ApiConnectionError({ code: 'switch-in-progress',
|
|
39
|
+
message: 'An account switch is waiting for confirmation. Confirm it or cancel it before signing in again.' });
|
|
40
|
+
}
|
|
41
|
+
if (intent === 'switch-account' && (record === null || record.account === null)) {
|
|
42
|
+
throw new ApiConnectionError({ code: 'not-connected', message: 'There is no connected account to switch from. Connect an account first.' });
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/** A connected record whose stored tokens this host can read and that hold a refresh token. */
|
|
46
|
+
async function holdsRenewableCredential(deps, record) {
|
|
47
|
+
if (record?.status !== 'connected')
|
|
48
|
+
return false;
|
|
49
|
+
return (await loadReadableTokens(deps, { key: record.key }))?.refreshToken != null;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The client kind's fixed parameters, plus the descriptor's force-consent ones on a hosted start
|
|
53
|
+
* with nothing renewable stored for the account: a provider may issue a refresh token only on the
|
|
54
|
+
* first consent per account and client (e.g. the same account in a second workspace). A switch
|
|
55
|
+
* signs in another account, so the stored credential never counts for it.
|
|
56
|
+
*/
|
|
57
|
+
async function clientKindParams(deps, record, intent) {
|
|
58
|
+
const fixed = deps.descriptor.authorizationParams[deps.clientKind];
|
|
59
|
+
if (deps.clientKind === 'public')
|
|
60
|
+
return fixed;
|
|
61
|
+
const renewable = intent === 'connect' && await holdsRenewableCredential(deps, record);
|
|
62
|
+
return renewable ? fixed : { ...fixed, ...deps.descriptor.forceConsentParams };
|
|
63
|
+
}
|
|
64
|
+
/** Map OAuth core failures to connection codes; the core's messages are already token-free. */
|
|
65
|
+
function toConnectionError(error) {
|
|
66
|
+
if (!(error instanceof OAuthError))
|
|
67
|
+
return error;
|
|
68
|
+
if (error.code === 'OAUTH_INVALID_STATE')
|
|
69
|
+
return invalidAttempt({}, { cause: error });
|
|
70
|
+
const code = error.code === 'OAUTH_ACCESS_DENIED' ? 'access-denied' : 'authorization-failed';
|
|
71
|
+
return new ApiConnectionError({ code, message: `Sign-in did not complete: ${error.message}. ${error.operatorAction}` }, { cause: error });
|
|
72
|
+
}
|
|
73
|
+
export async function startApiConnectionAuthorization(deps, requiredArgs, optionalArgs = {}) {
|
|
74
|
+
const { workspaceId, actorId, intent } = requiredArgs;
|
|
75
|
+
assertId(workspaceId, 'workspaceId');
|
|
76
|
+
assertId(actorId, 'actorId');
|
|
77
|
+
if (intent !== 'connect' && intent !== 'switch-account')
|
|
78
|
+
throw requestInvalid('intent');
|
|
79
|
+
const startParams = checkStartParams(deps.descriptor.startParams, optionalArgs.startParams ?? {});
|
|
80
|
+
const key = deriveApiConnectionKey({ workspaceId, pluginId: deps.descriptor.pluginId, connectionId: deps.descriptor.connectionId });
|
|
81
|
+
const record = await deps.records.read({ key });
|
|
82
|
+
assertStartAllowed(record, intent);
|
|
83
|
+
const requestedScopes = checkScopes(await deps.hooks.resolveScopes({ scopeSetIds: [...requiredArgs.scopeSetIds] }));
|
|
84
|
+
const kindParams = await clientKindParams(deps, record, intent);
|
|
85
|
+
const ownerKey = ownerKeyFor(deps, { workspaceId, actorId });
|
|
86
|
+
const attemptId = generateOAuthState({ randomBytesFn: deps.randomBytesFn }, { stateBytes: ATTEMPT_ID_BYTES });
|
|
87
|
+
const browserBinding = generateOAuthState({ randomBytesFn: deps.randomBytesFn }, { stateBytes: BROWSER_BINDING_BYTES });
|
|
88
|
+
const draft = { key, attemptId, ownerKey, browserBindingHash: hashBrowserBinding(browserBinding), workspaceId, actorId, pluginId: deps.descriptor.pluginId,
|
|
89
|
+
connectionId: deps.descriptor.connectionId, intent, requestedScopes, generation: record?.generation ?? 0 };
|
|
90
|
+
const begun = await beginAuthorizationCode({
|
|
91
|
+
provider: providerFor(deps), stateless: attemptSealer(deps, { draft }), randomBytesFn: deps.randomBytesFn, guard: deps.guard,
|
|
92
|
+
options: deps.appOptions, ownerKey, client: deps.client, redirectUri: requiredArgs.redirectUri,
|
|
93
|
+
}, { scopes: requestedScopes, extraAuthorizationParams: { ...kindParams, ...startParams } })
|
|
94
|
+
.catch((error) => { throw toConnectionError(error); });
|
|
95
|
+
return { connectionRef: key, authorizationUrl: begun.authorizationUrl, state: begun.state, attemptId, browserBinding,
|
|
96
|
+
expiresAt: begun.expiresAt };
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Redeem the callback. `redirectUri` is the exact callback URL this request arrived on and the
|
|
100
|
+
* identities are the host's authenticated session, never values read from the callback itself.
|
|
101
|
+
* `browserBinding` is what the callback's browser carried back (`''` when it carried none); a
|
|
102
|
+
* missing or different binding burns the attempt with the same `invalid-attempt`.
|
|
103
|
+
*/
|
|
104
|
+
export async function completeApiConnectionAuthorization(deps, requiredArgs) {
|
|
105
|
+
assertId(requiredArgs.workspaceId, 'workspaceId');
|
|
106
|
+
assertId(requiredArgs.actorId, 'actorId');
|
|
107
|
+
if (!URL.canParse(requiredArgs.redirectUri))
|
|
108
|
+
throw requestInvalid('redirectUri');
|
|
109
|
+
const params = checkCallbackParams(requiredArgs.callbackParams);
|
|
110
|
+
const callbackFields = pickBoundedFields(deps.descriptor.callbackFields, requiredArgs.callbackParams, 'callback field');
|
|
111
|
+
let attempt;
|
|
112
|
+
const tokens = await completeAuthorizationCode({
|
|
113
|
+
provider: providerFor(deps), stateless: attemptOpener(deps, { browserBinding: requiredArgs.browserBinding, onOpen: opened => { attempt = opened.attempt; } }),
|
|
114
|
+
redirectUri: new URL(requiredArgs.redirectUri).href, ownerKey: ownerKeyFor(deps, requiredArgs), client: deps.client, params,
|
|
115
|
+
fetchFn: deps.fetchFn, guard: deps.guard, clock: deps.clock,
|
|
116
|
+
}).catch((error) => { throw toConnectionError(error); });
|
|
117
|
+
// completeAuthorizationCode only reaches the exchange after `open` returned an attempt.
|
|
118
|
+
return finishAuthorization(deps, { attempt: attempt, tokens, callbackFields });
|
|
119
|
+
}
|
|
120
|
+
//# sourceMappingURL=authorization.js.map
|