@kubun/plugin-connector 0.13.1 → 0.14.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.
package/lib/action.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import type { CredentialProvider, EntityRecord, WriteAttachment } from '@kubun/connector';
1
+ import type { EntityRecord, WriteAttachment } from '@kubun/connector';
2
+ import type { CredentialProvider } from '@kubun/credential-types';
2
3
  import type { StoreProvider } from '@kubun/db';
3
4
  import type { Logger } from '@kubun/logger';
4
5
  import type { ConnectorRegistry } from './registry.js';
package/lib/api.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { type MethodRegistry } from '@kokuin/token';
2
- import { type CredentialManager } from '@kubun/credential';
3
1
  import type { StoreProvider } from '@kubun/db';
4
2
  import type { Logger } from '@kubun/logger';
5
3
  import { type PendingAuthRecord } from '@kubun/store-connector';
4
+ export type { CreateCredentialAPIParams, CredentialAPI } from '@kubun/credential';
5
+ export { createCredentialAPI } from '@kubun/credential';
6
6
  export type SyncStateData = {
7
7
  connectorName: string;
8
8
  ownerDID: string;
@@ -28,70 +28,18 @@ export type SetSyncStateParams = {
28
28
  * two `owner_did` columns are equality keys, so an un-normalized one files the
29
29
  * same account under two rows: a credential invisible under one spelling and
30
30
  * un-revokable under the other, and a sync lease held twice at once.
31
- *
32
- * `ownerWrappableDID` is NOT normalized — see {@link createConnectorAPI}.
33
31
  */
34
32
  export type ConnectorAPI = {
35
33
  getSyncState: (connectorName: string, ownerDID: string) => Promise<SyncStateData | null>;
36
34
  setSyncState: (connectorName: string, ownerDID: string, state: SetSyncStateParams) => Promise<SyncStateData>;
37
35
  deleteSyncState: (connectorName: string, ownerDID: string) => Promise<void>;
38
36
  listSyncStates: (connectorName: string) => Promise<Array<SyncStateData>>;
39
- getCredential: (providerName: string, ownerDID: string) => Promise<string | null>;
40
- getCredentialProvenance: (providerName: string, ownerDID: string) => Promise<{
41
- updatedAt: string | null;
42
- writerDID: string | null;
43
- } | null>;
44
- /**
45
- * Re-encrypt an existing credential. Refuses when none exists, because
46
- * creating one is a different decision — see `createCredential`.
47
- */
48
- setCredential: (providerName: string, ownerDID: string, credential: string) => Promise<void>;
49
- /**
50
- * Mint the key, its two wrappings and the entry, and record the pointer.
51
- *
52
- * Split from `setCredential` so the headless refresh path cannot mint a key.
53
- * A minted key fixes who will ever be able to read it, and a refresh running
54
- * with no owner in hand would mint one wrapped to the server alone — locking
55
- * the account owner out of their own credential with nothing failing.
56
- */
57
- createCredential: (params: {
58
- providerName: string;
59
- ownerDID: string;
60
- ownerWrappableDID: string;
61
- controllerWrappableDID?: string;
62
- credential: string;
63
- }) => Promise<void>;
64
- deleteCredential: (providerName: string, ownerDID: string) => Promise<void>;
65
37
  createPendingAuth: (record: PendingAuthRecord) => Promise<void>;
66
38
  consumePendingAuth: (state: string) => Promise<PendingAuthRecord | null>;
67
39
  deleteExpiredPendingAuth: (cutoffMs: number) => Promise<void>;
68
- /**
69
- * The controller resolvers for this API's (request-scoped) transaction
70
- * provider — the exact `methods` the credential mint passes to `createKey`.
71
- * Exposed so the OAuth pre-flight can ask `canWrapTo` with the same resolver
72
- * the mint uses, rather than failing closed on a `did:kokuin:` owner whose
73
- * agreement key is resolvable only through the controller resolver.
74
- */
75
- getControllerMethods: () => MethodRegistry;
76
40
  };
77
41
  export type CreateConnectorAPIParams = {
78
42
  stores: StoreProvider;
79
43
  logger: Logger;
80
- /**
81
- * Takes the `StoreProvider` rather than a manager, because during a mutation
82
- * that provider is the transaction and a manager built over the base one
83
- * would read outside it.
84
- */
85
- getCredentialManager: (stores: StoreProvider) => Promise<CredentialManager>;
86
- /** The engine's own DID, in a form that can be encrypted to. */
87
- serverWrappableDID: string;
88
- /**
89
- * Resolvers for wrapping recipients that carry no key material of their own
90
- * (`did:kokuin:`), scoped to the request's transaction provider so a resolve
91
- * reads the mutation's tx, never a second connection. A self-contained
92
- * recipient resolves with an empty registry, so callers with no controller
93
- * recipient in play still pass `() => []`.
94
- */
95
- getControllerMethods: (stores: StoreProvider) => MethodRegistry;
96
44
  };
97
45
  export declare function createConnectorAPI(params: CreateConnectorAPIParams): ConnectorAPI;
package/lib/api.js CHANGED
@@ -1,10 +1,8 @@
1
1
  import { normalizeDID } from '@kokuin/token';
2
- import { CredentialSupersededBranch } from '@kubun/credential';
3
2
  import { getConnectorStore } from '@kubun/store-connector';
4
- import { fromUTF, toUTF } from '@sozai/codec';
3
+ export { createCredentialAPI } from '@kubun/credential';
5
4
  export function createConnectorAPI(params) {
6
5
  const getStore = ()=>getConnectorStore(params.stores);
7
- const getCredentials = ()=>params.getCredentialManager(params.stores);
8
6
  return {
9
7
  async getSyncState (connectorName, ownerDID) {
10
8
  const store = await getStore();
@@ -68,116 +66,6 @@ export function createConnectorAPI(params) {
68
66
  leaseExpiresAt: entry.leaseExpiresAt ?? null
69
67
  }));
70
68
  },
71
- async getCredential (providerName, ownerDID) {
72
- const store = await getStore();
73
- const entryID = await store.getCredentialEntryID(providerName, normalizeDID(ownerDID));
74
- if (entryID == null) return null;
75
- try {
76
- return toUTF(await (await getCredentials()).readEntry(entryID));
77
- } catch (error) {
78
- if (error instanceof CredentialSupersededBranch) {
79
- params.logger.warn('Credential entry {entryID} for provider {providerName} belongs to a superseded branch', {
80
- providerName,
81
- entryID
82
- });
83
- return null;
84
- }
85
- throw error;
86
- }
87
- },
88
- async getCredentialProvenance (providerName, ownerDID) {
89
- // Reflects the current pointer, not the winning branch — no superseded-branch guard
90
- // (it never decrypts). Callers must gate on getCredential() != null so a loser-branch
91
- // pointer's provenance is never surfaced.
92
- const store = await getStore();
93
- const entryID = await store.getCredentialEntryID(providerName, normalizeDID(ownerDID));
94
- if (entryID == null) return null;
95
- return (await getCredentials()).getEntryProvenance(entryID);
96
- },
97
- async setCredential (providerName, ownerDID, credential) {
98
- const store = await getStore();
99
- const entryID = await store.getCredentialEntryID(providerName, normalizeDID(ownerDID));
100
- if (entryID == null) {
101
- throw new Error(`No connector credential to update for provider "${providerName}"; create it through the authorization flow`);
102
- }
103
- // Opens the key through the server's own wrapping and rewrites the entry
104
- // under it. No key is minted and no wrapping is touched, so a refresh
105
- // cannot change who can read the credential.
106
- await (await getCredentials()).updateEntry(entryID, fromUTF(credential));
107
- },
108
- async createCredential (input) {
109
- const { providerName, ownerDID, ownerWrappableDID, credential } = input;
110
- const store = await getStore();
111
- const credentials = await getCredentials();
112
- // Wrapping to a DID needs only that DID's published key, so an engine that
113
- // cannot decrypt would mint this key perfectly and then be unable to read
114
- // it — a failure that surfaces at the first headless sync, far from here.
115
- // This is where `cipher == null` used to fail closed, and it still does.
116
- if (!credentials.availableFactors().includes('did')) {
117
- throw new Error(`Cannot create a connector credential for "${providerName}": this engine's identity cannot decrypt, so it could never read back what it stored`);
118
- }
119
- // Two wrappings from the first write, not one plus a later grant: the
120
- // server has to read this to run sync, and the owner has to be able to
121
- // rotate and revoke it. Owner is authority, a different question from who
122
- // can decrypt: when a controller is supplied it is the owner, so a device
123
- // revoke goes through the controller's capability chain rather than the
124
- // device self-authorizing; absent one the device owns its own key.
125
- //
126
- // The two spellings below are deliberately different questions about the
127
- // same identity, and NOT interchangeable: `owner_did` is an equality key
128
- // and so is normalized, while a recipient is encrypted to and must keep
129
- // its wrappable form. Normalizing a `did:peer:4` recipient hands the short
130
- // form to `deriveSharedSecret`, which resolves no document and no
131
- // agreement key — do not fold these together.
132
- const wrappings = [
133
- [
134
- {
135
- kind: 'did',
136
- recipientDID: ownerWrappableDID
137
- }
138
- ],
139
- [
140
- {
141
- kind: 'did',
142
- recipientDID: params.serverWrappableDID
143
- }
144
- ]
145
- ];
146
- // A recovery recipient (e.g. a controller / seed-holder), so the credential
147
- // survives device loss. Opt-in: absent when the caller supplied none. Kept
148
- // in its wrappable form for the same reason as the two above — it is
149
- // encrypted to, not compared against.
150
- if (input.controllerWrappableDID != null) {
151
- wrappings.push([
152
- {
153
- kind: 'did',
154
- recipientDID: input.controllerWrappableDID
155
- }
156
- ]);
157
- }
158
- // The controller owns the key when supplied (its canonical DID equals the
159
- // normalized wrappable form); the account pointer below stays keyed on the
160
- // device — ownership and account scoping are separate concerns.
161
- const keyOwnerDID = input.controllerWrappableDID != null ? normalizeDID(input.controllerWrappableDID) : normalizeDID(ownerDID);
162
- const keyID = await credentials.createKey({
163
- ownerDID: keyOwnerDID,
164
- wrappings,
165
- methods: params.getControllerMethods(params.stores)
166
- });
167
- const entryID = await credentials.putEntry(keyID, fromUTF(credential));
168
- await store.setCredentialEntryID(providerName, normalizeDID(ownerDID), entryID);
169
- },
170
- async deleteCredential (providerName, ownerDID) {
171
- const store = await getStore();
172
- const owner = normalizeDID(ownerDID);
173
- const entryID = await store.getCredentialEntryID(providerName, owner);
174
- await store.deleteCredentialEntryID(providerName, owner);
175
- if (entryID != null) {
176
- // The pointer and the entry go together. Leaving the entry would keep
177
- // the token readable by anyone who kept its id after a disconnect.
178
- await (await getCredentials()).deleteEntry(entryID);
179
- }
180
- },
181
69
  async createPendingAuth (record) {
182
70
  const store = await getStore();
183
71
  await store.createPendingAuth(record);
@@ -189,9 +77,6 @@ export function createConnectorAPI(params) {
189
77
  async deleteExpiredPendingAuth (cutoffMs) {
190
78
  const store = await getStore();
191
79
  await store.deleteExpiredPendingAuth(cutoffMs);
192
- },
193
- getControllerMethods () {
194
- return params.getControllerMethods(params.stores);
195
80
  }
196
81
  };
197
82
  }
@@ -1,22 +1,2 @@
1
- import type { Credential, CredentialProvider, OAuthProviderDefinition } from '@kubun/connector';
2
- import type { Runtime } from '@sozai/runtime';
3
- import type { ConnectorAPI } from './api.js';
4
- export type DBCredentialProviderParams = {
5
- api: ConnectorAPI;
6
- runtime: Runtime;
7
- providers: Array<OAuthProviderDefinition>;
8
- bufferSeconds?: number;
9
- };
10
- export declare class DBCredentialProvider implements CredentialProvider {
11
- #private;
12
- constructor(params: DBCredentialProviderParams);
13
- get(providerName: string, ownerDID: string): Promise<Credential | null>;
14
- set(params: {
15
- providerName: string;
16
- ownerDID: string;
17
- credential: Credential;
18
- ownerWrappableDID?: string;
19
- controllerWrappableDID?: string;
20
- }): Promise<void>;
21
- delete(providerName: string, ownerDID: string): Promise<void>;
22
- }
1
+ export type { DBCredentialProviderParams } from '@kubun/credential';
2
+ export { DBCredentialProvider } from '@kubun/credential';
package/lib/credential.js CHANGED
@@ -1,129 +1,4 @@
1
- const DEFAULT_BUFFER_SECONDS = 300;
2
- function serializeCredential(credential) {
3
- const serialized = {
4
- accessToken: credential.accessToken,
5
- scopes: credential.scopes
6
- };
7
- if (credential.refreshToken != null) {
8
- serialized.refreshToken = credential.refreshToken;
9
- }
10
- if (credential.expiresAt != null) {
11
- serialized.expiresAt = credential.expiresAt.toISOString();
12
- }
13
- if (credential.accountLabel != null) {
14
- serialized.accountLabel = credential.accountLabel;
15
- }
16
- if (credential.metadata != null) {
17
- serialized.metadata = credential.metadata;
18
- }
19
- return JSON.stringify(serialized);
20
- }
21
- function deserializeCredential(raw) {
22
- // ParseJSONResultsPlugin may have already parsed the JSON string
23
- const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;
24
- const credential = {
25
- accessToken: parsed.accessToken,
26
- scopes: parsed.scopes
27
- };
28
- if (parsed.refreshToken != null) {
29
- credential.refreshToken = parsed.refreshToken;
30
- }
31
- if (parsed.expiresAt != null) {
32
- credential.expiresAt = new Date(parsed.expiresAt);
33
- }
34
- if (parsed.accountLabel != null) {
35
- credential.accountLabel = parsed.accountLabel;
36
- }
37
- if (parsed.metadata != null) {
38
- credential.metadata = parsed.metadata;
39
- }
40
- return credential;
41
- }
42
- export class DBCredentialProvider {
43
- #api;
44
- #runtime;
45
- #providers;
46
- #bufferMs;
47
- constructor(params){
48
- this.#api = params.api;
49
- this.#runtime = params.runtime;
50
- this.#providers = params.providers;
51
- this.#bufferMs = (params.bufferSeconds ?? DEFAULT_BUFFER_SECONDS) * 1000;
52
- }
53
- async get(providerName, ownerDID) {
54
- const raw = await this.#api.getCredential(providerName, ownerDID);
55
- if (raw == null) return null;
56
- const credential = deserializeCredential(raw);
57
- if (this.#isExpiringSoon(credential) && credential.refreshToken != null) {
58
- const refreshed = await this.#refresh(providerName, ownerDID, credential, credential.refreshToken);
59
- return refreshed ?? credential;
60
- }
61
- return credential;
62
- }
63
- async set(params) {
64
- const { providerName, ownerDID, credential, ownerWrappableDID, controllerWrappableDID } = params;
65
- const serialized = serializeCredential(credential);
66
- // Update when one exists, mint only when it does not. Dispatching on
67
- // presence rather than on the caller keeps the refresh path unable to mint
68
- // even when it does hold a wrappable DID.
69
- if (await this.#api.getCredential(providerName, ownerDID) != null) {
70
- await this.#api.setCredential(providerName, ownerDID, serialized);
71
- return;
72
- }
73
- if (ownerWrappableDID == null) {
74
- throw new Error(`Cannot create a connector credential for "${providerName}" without the owner's wrappable DID`);
75
- }
76
- await this.#api.createCredential({
77
- providerName,
78
- ownerDID,
79
- ownerWrappableDID,
80
- controllerWrappableDID,
81
- credential: serialized
82
- });
83
- }
84
- async delete(providerName, ownerDID) {
85
- await this.#api.deleteCredential(providerName, ownerDID);
86
- }
87
- #isExpiringSoon(credential) {
88
- if (credential.expiresAt == null) return false;
89
- return credential.expiresAt.getTime() - Date.now() < this.#bufferMs;
90
- }
91
- async #refresh(providerName, ownerDID, credential, refreshToken) {
92
- const provider = this.#providers.find((p)=>p.name === providerName);
93
- if (provider == null || provider.clientID == null || provider.clientSecret == null) {
94
- return null;
95
- }
96
- try {
97
- const response = await this.#runtime.fetch(provider.tokenEndpoint, {
98
- method: 'POST',
99
- headers: {
100
- 'Content-Type': 'application/x-www-form-urlencoded'
101
- },
102
- body: new URLSearchParams({
103
- grant_type: 'refresh_token',
104
- refresh_token: refreshToken,
105
- client_id: provider.clientID,
106
- client_secret: provider.clientSecret
107
- })
108
- });
109
- if (!response.ok) return null;
110
- const tokenData = await response.json();
111
- const refreshed = {
112
- accessToken: tokenData.access_token,
113
- refreshToken: tokenData.refresh_token ?? credential.refreshToken,
114
- expiresAt: tokenData.expires_in != null ? new Date(Date.now() + tokenData.expires_in * 1000) : undefined,
115
- scopes: tokenData.scope?.split(' ') ?? credential.scopes,
116
- accountLabel: credential.accountLabel,
117
- metadata: credential.metadata
118
- };
119
- await this.set({
120
- providerName,
121
- ownerDID,
122
- credential: refreshed
123
- });
124
- return refreshed;
125
- } catch {
126
- return null;
127
- }
128
- }
129
- }
1
+ // The DB-backed credential provider moved to @kubun/credential; re-exported here
2
+ // so existing importers of `../src/credential.js` and the package index keep
3
+ // resolving it.
4
+ export { DBCredentialProvider } from '@kubun/credential';
package/lib/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
- import type { ConnectorDefinition, OAuthProviderDefinition, SyncBoundary } from '@kubun/connector';
1
+ import type { ConnectorDefinition, SyncBoundary } from '@kubun/connector';
2
+ import type { OAuthProviderDefinition } from '@kubun/credential-types';
2
3
  import type { KubunPlugin, PluginFactoryParams } from '@kubun/engine';
3
- import { type ConnectorAPI, type SetSyncStateParams, type SyncStateData } from './api.js';
4
+ import type { AdaptivePolicy } from '@kubun/plugin-workflow-api';
5
+ import { type ConnectorAPI, type CredentialAPI, type SetSyncStateParams, type SyncStateData } from './api.js';
4
6
  import { DBCredentialProvider, type DBCredentialProviderParams } from './credential.js';
5
7
  export { type ExecuteActionDeps, type ExecuteActionParams, type ExecuteActionResult, executeAction, } from './action.js';
6
8
  export { type ConnectorActivatedEvent, type ConnectorDeactivatedEvent, ConnectorManager, type ConnectorManagerEvents, type ConnectorManagerParams, } from './manager.js';
@@ -13,13 +15,14 @@ export { type OrchestrateSyncParams, type OrchestrateSyncResult, orchestrateSync
13
15
  export { EntityProcessor, type EntityProcessorParams, type MutateDocuments, type ProcessBatchResult, type SignedDocumentWriter, } from './sync/processor.js';
14
16
  export { DBSyncStateStore } from './sync/state.js';
15
17
  export { CONNECTOR_SYNC_CONCURRENCY, CONNECTOR_SYNC_WORKFLOW, type ConnectorSyncWorkflowDefinition, type ConnectorSyncWorkflowParams, createConnectorSyncWorkflow, } from './sync/workflow.js';
16
- export type { ConnectorAPI, SetSyncStateParams, SyncStateData };
18
+ export type { ConnectorAPI, CredentialAPI, SetSyncStateParams, SyncStateData };
17
19
  export { DBCredentialProvider, type DBCredentialProviderParams };
18
20
  export type ConnectorPluginOptions = {
19
21
  connectors: Array<ConnectorDefinition>;
20
22
  providers?: Array<OAuthProviderDefinition>;
21
23
  defaults?: {
22
24
  boundary?: SyncBoundary;
25
+ periodicSyncPolicy?: AdaptivePolicy;
23
26
  };
24
27
  };
25
28
  export declare function createConnectorPlugin(options: ConnectorPluginOptions): (params: PluginFactoryParams) => KubunPlugin;