@party-stack/connect 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +189 -2
- package/lib/ServiceConnector.d.ts +68 -0
- package/lib/ServiceConnector.d.ts.map +1 -0
- package/lib/ServiceConnector.js +1 -0
- package/lib/acquireConfiguredConnection.d.ts +32 -0
- package/lib/acquireConfiguredConnection.d.ts.map +1 -0
- package/lib/acquireConfiguredConnection.js +54 -0
- package/lib/acquireConfiguredConnection.js.map +1 -0
- package/lib/authentication.d.ts +76 -0
- package/lib/authentication.d.ts.map +1 -0
- package/lib/authentication.js +95 -0
- package/lib/authentication.js.map +1 -0
- package/lib/authorization.d.ts +43 -0
- package/lib/authorization.d.ts.map +1 -0
- package/lib/authorization.js +175 -0
- package/lib/authorization.js.map +1 -0
- package/lib/core/accessToken.d.ts +10 -0
- package/lib/core/accessToken.d.ts.map +1 -0
- package/lib/core/accessToken.js +87 -0
- package/lib/core/accessToken.js.map +1 -0
- package/lib/core/backend.d.ts +33 -0
- package/lib/core/backend.d.ts.map +1 -0
- package/lib/core/backend.js +249 -0
- package/lib/core/backend.js.map +1 -0
- package/lib/core/errors.d.ts +13 -0
- package/lib/core/errors.d.ts.map +1 -0
- package/lib/core/errors.js +26 -0
- package/lib/core/errors.js.map +1 -0
- package/lib/core/maintenance.d.ts +11 -0
- package/lib/core/maintenance.d.ts.map +1 -0
- package/lib/core/maintenance.js +21 -0
- package/lib/core/maintenance.js.map +1 -0
- package/lib/core/migrate.d.ts +18 -0
- package/lib/core/migrate.d.ts.map +1 -0
- package/lib/core/migrate.js +71 -0
- package/lib/core/migrate.js.map +1 -0
- package/lib/core/oauth.d.ts +27 -0
- package/lib/core/oauth.d.ts.map +1 -0
- package/lib/core/oauth.js +82 -0
- package/lib/core/oauth.js.map +1 -0
- package/lib/core/oauthAuthority.d.ts +90 -0
- package/lib/core/oauthAuthority.d.ts.map +1 -0
- package/lib/core/oauthAuthority.js +382 -0
- package/lib/core/oauthAuthority.js.map +1 -0
- package/lib/core/store.d.ts +48 -0
- package/lib/core/store.d.ts.map +1 -0
- package/lib/core/store.js +92 -0
- package/lib/core/store.js.map +1 -0
- package/lib/createDefaultConnectionEgressHandlers.d.ts +5 -0
- package/lib/createDefaultConnectionEgressHandlers.d.ts.map +1 -0
- package/lib/createDefaultConnectionEgressHandlers.js +20 -0
- package/lib/createDefaultConnectionEgressHandlers.js.map +1 -0
- package/lib/index.d.ts +20 -0
- package/lib/index.js +17 -0
- package/lib/makeConnectManager.d.ts +90 -0
- package/lib/makeConnectManager.d.ts.map +1 -0
- package/lib/makeConnectManager.js +91 -0
- package/lib/makeConnectManager.js.map +1 -0
- package/lib/oauth/storage.d.ts +9 -0
- package/lib/oauth/storage.d.ts.map +1 -0
- package/lib/oauth/storage.js +16 -0
- package/lib/oauth/storage.js.map +1 -0
- package/lib/publicOntology.d.ts +17 -0
- package/lib/publicOntology.d.ts.map +1 -0
- package/lib/publicOntology.js +86 -0
- package/lib/publicOntology.js.map +1 -0
- package/lib/server/index.d.ts +33 -0
- package/lib/server/index.d.ts.map +1 -0
- package/lib/server/index.js +119 -0
- package/lib/server/index.js.map +1 -0
- package/lib/serverClient.d.ts +28 -0
- package/lib/serverClient.d.ts.map +1 -0
- package/lib/serverClient.js +67 -0
- package/lib/serverClient.js.map +1 -0
- package/lib/serviceConnections.d.ts +39 -0
- package/lib/serviceConnections.d.ts.map +1 -0
- package/lib/serviceConnections.js +277 -0
- package/lib/serviceConnections.js.map +1 -0
- package/lib/spec/index.d.ts +958 -0
- package/lib/spec/index.d.ts.map +1 -0
- package/lib/spec/index.js +565 -0
- package/lib/spec/index.js.map +1 -0
- package/lib/toWebEgress.d.ts +12 -0
- package/lib/toWebEgress.d.ts.map +1 -0
- package/lib/toWebEgress.js +28 -0
- package/lib/toWebEgress.js.map +1 -0
- package/lib/types.d.ts +44 -0
- package/lib/types.d.ts.map +1 -0
- package/lib/types.js +25 -0
- package/lib/types.js.map +1 -0
- package/lib/withHttpAuthenticationErrors.d.ts +5 -0
- package/lib/withHttpAuthenticationErrors.d.ts.map +1 -0
- package/lib/withHttpAuthenticationErrors.js +20 -0
- package/lib/withHttpAuthenticationErrors.js.map +1 -0
- package/package.json +34 -3
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
import { connectError } from "./errors.js";
|
|
2
|
+
import { and, eq, field, lte, ne } from "@party-stack/ontology-storage";
|
|
3
|
+
import { Clock, Context, Effect, Layer, Redacted, Schema } from "effect";
|
|
4
|
+
import * as oauth4webapi from "oauth4webapi";
|
|
5
|
+
import { Temporal } from "temporal-polyfill";
|
|
6
|
+
//#region src/core/oauthAuthority.ts
|
|
7
|
+
var OAuthAuthority = class OAuthAuthority extends Context.Service()("@party-stack/connect/OAuthAuthority") {
|
|
8
|
+
static layer = (options) => Layer.effect(OAuthAuthority, makeOAuthAuthority(options));
|
|
9
|
+
};
|
|
10
|
+
const instant = (milliseconds) => Temporal.Instant.fromEpochMilliseconds(milliseconds);
|
|
11
|
+
const expired = (time, now) => time !== void 0 && time.epochMilliseconds <= now;
|
|
12
|
+
const guardUrl = (value) => Effect.try({
|
|
13
|
+
try: () => {
|
|
14
|
+
const url = new URL(value);
|
|
15
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && [
|
|
16
|
+
"localhost",
|
|
17
|
+
"127.0.0.1",
|
|
18
|
+
"[::1]"
|
|
19
|
+
].includes(url.hostname))) throw new Error();
|
|
20
|
+
return url;
|
|
21
|
+
},
|
|
22
|
+
catch: () => connectError("Configuration", "OAuth URLs require HTTPS (or HTTP on localhost).")
|
|
23
|
+
});
|
|
24
|
+
/** One credential authority, usable by both device and HTTP entry points. */
|
|
25
|
+
const makeOAuthAuthority = (options) => Effect.sync(() => {
|
|
26
|
+
const { store, values } = options;
|
|
27
|
+
const read = Effect.fnUntraced(function* (id) {
|
|
28
|
+
const record = yield* store.get("OAuthConnection", id);
|
|
29
|
+
if (!record) return yield* connectError("NotFound", "Connection is unavailable.");
|
|
30
|
+
return record;
|
|
31
|
+
});
|
|
32
|
+
const configured = Effect.fnUntraced(function* (id) {
|
|
33
|
+
const application = yield* store.get("OAuthApplication", id);
|
|
34
|
+
if (!application) return yield* connectError("NotFound", "OAuth application is unavailable.");
|
|
35
|
+
const serviceInstance = yield* store.get("ServiceInstance", application.serviceInstance);
|
|
36
|
+
if (!serviceInstance) return yield* connectError("NotFound", "Service instance is unavailable.");
|
|
37
|
+
return {
|
|
38
|
+
application,
|
|
39
|
+
oauth: yield* options.oauth({
|
|
40
|
+
application,
|
|
41
|
+
serviceInstance
|
|
42
|
+
})
|
|
43
|
+
};
|
|
44
|
+
});
|
|
45
|
+
const decrypt = (value) => values.decrypt(Schema.String, value).pipe(Effect.map(Redacted.make), Effect.mapError(() => connectError("Storage", "Credential decryption failed.")));
|
|
46
|
+
const encrypt = (value) => values.encrypt(Schema.String, value).pipe(Effect.mapError(() => connectError("Storage", "Credential encryption failed.")));
|
|
47
|
+
const evict = (value) => value ? values.evict(value).pipe(Effect.mapError(() => connectError("Storage", "Credential deletion failed.", true))) : Effect.void;
|
|
48
|
+
const saveTokens = Effect.fnUntraced(function* (record, tokens) {
|
|
49
|
+
if (record.userId && record.userId !== tokens.userId) return yield* connectError("NeedsAuthentication", "Provider identity changed; reconnect explicitly.");
|
|
50
|
+
const next = {
|
|
51
|
+
...record,
|
|
52
|
+
status: "active",
|
|
53
|
+
userId: tokens.userId,
|
|
54
|
+
accessToken: yield* encrypt(tokens.accessToken),
|
|
55
|
+
accessTokenExpiresAt: tokens.accessTokenExpiresAt,
|
|
56
|
+
refreshToken: tokens.refreshToken ? yield* encrypt(tokens.refreshToken) : void 0,
|
|
57
|
+
refreshTokenExpiresAt: tokens.refreshToken ? tokens.refreshTokenExpiresAt : void 0,
|
|
58
|
+
grantedScopes: tokens.grantedScopes,
|
|
59
|
+
operationId: void 0,
|
|
60
|
+
operationExpiresAt: void 0
|
|
61
|
+
};
|
|
62
|
+
yield* store.put("OAuthConnection", next);
|
|
63
|
+
yield* evict(record.accessToken);
|
|
64
|
+
yield* evict(record.refreshToken);
|
|
65
|
+
return next;
|
|
66
|
+
});
|
|
67
|
+
const busy = Effect.fnUntraced(function* (record, recovery = false) {
|
|
68
|
+
if (!record.operationId) return;
|
|
69
|
+
const now = yield* Clock.currentTimeMillis;
|
|
70
|
+
if (!expired(record.operationExpiresAt, now)) return yield* connectError("Busy", "Connection operation is in progress.", true);
|
|
71
|
+
if (recovery) return;
|
|
72
|
+
return yield* connectError("NeedsAuthentication", "An interrupted credential operation requires reconnection.");
|
|
73
|
+
});
|
|
74
|
+
const finish = Effect.fnUntraced(function* (record, id) {
|
|
75
|
+
const current = yield* read(record.id);
|
|
76
|
+
if (current.operationId !== id) return yield* connectError("Busy", "Connection changed during the credential operation.");
|
|
77
|
+
return current;
|
|
78
|
+
});
|
|
79
|
+
const refresh = Effect.fn("Connect.refresh")(function* (connectionId) {
|
|
80
|
+
const operationId = crypto.randomUUID();
|
|
81
|
+
const record = yield* store.transaction(Effect.gen(function* () {
|
|
82
|
+
const current = yield* read(connectionId);
|
|
83
|
+
yield* busy(current);
|
|
84
|
+
if (current.status !== "active") return yield* connectError("NeedsAuthentication", "Reconnect this connection.");
|
|
85
|
+
const next = {
|
|
86
|
+
...current,
|
|
87
|
+
operationId,
|
|
88
|
+
operationExpiresAt: instant((yield* Clock.currentTimeMillis) + 6e4)
|
|
89
|
+
};
|
|
90
|
+
yield* store.put("OAuthConnection", next);
|
|
91
|
+
return next;
|
|
92
|
+
}));
|
|
93
|
+
return yield* Effect.gen(function* () {
|
|
94
|
+
const { application, oauth } = yield* configured(record.application);
|
|
95
|
+
let tokens;
|
|
96
|
+
if (application.flow === "client-credentials") tokens = yield* oauth.clientCredentials;
|
|
97
|
+
else {
|
|
98
|
+
if (!record.refreshToken || expired(record.refreshTokenExpiresAt, yield* Clock.currentTimeMillis)) return yield* connectError("NeedsAuthentication", "Refresh credentials are unavailable or expired.");
|
|
99
|
+
tokens = yield* oauth.refresh(Redacted.value(yield* decrypt(record.refreshToken)));
|
|
100
|
+
if (!tokens.refreshToken) tokens = {
|
|
101
|
+
...tokens,
|
|
102
|
+
refreshToken: Redacted.value(yield* decrypt(record.refreshToken)),
|
|
103
|
+
refreshTokenExpiresAt: record.refreshTokenExpiresAt
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
return yield* store.transaction(Effect.gen(function* () {
|
|
107
|
+
const current = yield* finish(record, operationId);
|
|
108
|
+
return yield* saveTokens(current, tokens);
|
|
109
|
+
}));
|
|
110
|
+
}).pipe(Effect.timeout(45e3), Effect.catchTag("TimeoutError", () => Effect.fail(connectError("NeedsAuthentication", "Credential exchange timed out; reconnect before retrying.")))).pipe(Effect.catch((error) => store.transaction(Effect.gen(function* () {
|
|
111
|
+
const current = yield* finish(record, operationId);
|
|
112
|
+
if (error.kind === "NeedsAuthentication") {
|
|
113
|
+
yield* evict(current.refreshToken);
|
|
114
|
+
yield* store.put("OAuthConnection", {
|
|
115
|
+
...current,
|
|
116
|
+
refreshToken: void 0,
|
|
117
|
+
refreshTokenExpiresAt: void 0,
|
|
118
|
+
status: "needs-auth",
|
|
119
|
+
operationId: void 0,
|
|
120
|
+
operationExpiresAt: void 0
|
|
121
|
+
});
|
|
122
|
+
} else if (error.kind !== "Storage") yield* store.put("OAuthConnection", {
|
|
123
|
+
...current,
|
|
124
|
+
operationId: void 0,
|
|
125
|
+
operationExpiresAt: void 0
|
|
126
|
+
});
|
|
127
|
+
})).pipe(Effect.andThen(Effect.fail(error)))));
|
|
128
|
+
});
|
|
129
|
+
return OAuthAuthority.of({
|
|
130
|
+
connectionForApplication: Effect.fn("Connect.connectionForApplication")(function* (applicationId) {
|
|
131
|
+
const application = yield* store.get("OAuthApplication", applicationId);
|
|
132
|
+
if (!application) return yield* connectError("NotFound", "OAuth application is unavailable.");
|
|
133
|
+
if (!application.connection) return;
|
|
134
|
+
const connection = yield* read(application.connection);
|
|
135
|
+
if (connection.application !== applicationId) return yield* connectError("Configuration", "OAuth application points to a connection belonging to another application.");
|
|
136
|
+
return connection;
|
|
137
|
+
}),
|
|
138
|
+
begin: Effect.fn("Connect.begin")(function* (input) {
|
|
139
|
+
yield* guardUrl(input.redirectUrl);
|
|
140
|
+
if (input.returnUrl) yield* guardUrl(input.returnUrl);
|
|
141
|
+
const { application, oauth } = yield* configured(input.applicationId);
|
|
142
|
+
if (application.redirectUrl && input.redirectUrl !== application.redirectUrl) return yield* connectError("Forbidden", "Redirect URL does not match the OAuth application.");
|
|
143
|
+
if (application.flow !== "authorization-code") return yield* connectError("Configuration", "This application does not support interactive authorization.");
|
|
144
|
+
const id = oauth4webapi.generateRandomState();
|
|
145
|
+
const verifier = oauth4webapi.generateRandomCodeVerifier();
|
|
146
|
+
const challenge = yield* Effect.tryPromise({
|
|
147
|
+
try: () => oauth4webapi.calculatePKCECodeChallenge(verifier),
|
|
148
|
+
catch: () => connectError("Configuration", "Could not generate PKCE challenge.")
|
|
149
|
+
});
|
|
150
|
+
const authorizationUrl = yield* oauth.authorizationUrl({
|
|
151
|
+
state: id,
|
|
152
|
+
codeChallenge: challenge,
|
|
153
|
+
redirectUrl: input.redirectUrl
|
|
154
|
+
});
|
|
155
|
+
yield* guardUrl(authorizationUrl);
|
|
156
|
+
yield* store.transaction(Effect.gen(function* () {
|
|
157
|
+
if (input.connectionId) {
|
|
158
|
+
const previous = yield* read(input.connectionId);
|
|
159
|
+
if (previous.application !== input.applicationId) return yield* connectError("Forbidden", "Connection belongs to another application.");
|
|
160
|
+
yield* busy(previous, true);
|
|
161
|
+
}
|
|
162
|
+
yield* store.put("OAuthAuthorizationAttempt", {
|
|
163
|
+
...input.properties,
|
|
164
|
+
id,
|
|
165
|
+
application: input.applicationId,
|
|
166
|
+
principalId: input.principalId,
|
|
167
|
+
connectionId: input.connectionId ?? crypto.randomUUID(),
|
|
168
|
+
redirectUrl: input.redirectUrl,
|
|
169
|
+
returnUrl: input.returnUrl,
|
|
170
|
+
codeVerifier: yield* encrypt(verifier),
|
|
171
|
+
expiresAt: instant((yield* Clock.currentTimeMillis) + 6e5),
|
|
172
|
+
status: "pending"
|
|
173
|
+
});
|
|
174
|
+
}));
|
|
175
|
+
return {
|
|
176
|
+
id,
|
|
177
|
+
authorizationUrl
|
|
178
|
+
};
|
|
179
|
+
}),
|
|
180
|
+
complete: Effect.fn("Connect.complete")(function* (input) {
|
|
181
|
+
const callback = yield* guardUrl(input.callbackUrl);
|
|
182
|
+
const id = callback.searchParams.get("state");
|
|
183
|
+
if (!id) return yield* connectError("InvalidAttempt", "Authorization attempt is unavailable.");
|
|
184
|
+
const attempt = yield* store.transaction(Effect.gen(function* () {
|
|
185
|
+
const current = yield* store.get("OAuthAuthorizationAttempt", id);
|
|
186
|
+
if (!current || current.principalId !== input.principalId || expired(current.expiresAt, yield* Clock.currentTimeMillis)) return yield* connectError("InvalidAttempt", "Authorization attempt is unavailable.");
|
|
187
|
+
const expected = new URL(current.redirectUrl);
|
|
188
|
+
if (expected.origin !== callback.origin || expected.pathname !== callback.pathname) return yield* connectError("InvalidAttempt", "Authorization callback URL does not match.");
|
|
189
|
+
if (current.status === "completed") return current;
|
|
190
|
+
if (current.status !== "pending") return yield* connectError("InvalidAttempt", "Authorization attempt was already consumed; start again.");
|
|
191
|
+
yield* store.put("OAuthAuthorizationAttempt", {
|
|
192
|
+
...current,
|
|
193
|
+
status: "exchanging"
|
|
194
|
+
});
|
|
195
|
+
return current;
|
|
196
|
+
}));
|
|
197
|
+
if (attempt.status === "completed") {
|
|
198
|
+
if (!attempt.connectionId) return yield* connectError("InvalidAttempt", "Completed authorization has no connection.");
|
|
199
|
+
return yield* read(attempt.connectionId);
|
|
200
|
+
}
|
|
201
|
+
return yield* Effect.gen(function* () {
|
|
202
|
+
const { application, oauth } = yield* configured(attempt.application);
|
|
203
|
+
const tokens = yield* oauth.exchange({
|
|
204
|
+
callbackUrl: input.callbackUrl,
|
|
205
|
+
state: id,
|
|
206
|
+
redirectUrl: attempt.redirectUrl,
|
|
207
|
+
codeVerifier: Redacted.value(yield* decrypt(attempt.codeVerifier))
|
|
208
|
+
});
|
|
209
|
+
const extra = options.connectionProperties ? yield* options.connectionProperties(attempt) : {};
|
|
210
|
+
return yield* store.transaction(Effect.gen(function* () {
|
|
211
|
+
const claimed = yield* store.get("OAuthAuthorizationAttempt", id);
|
|
212
|
+
if (!claimed || claimed.status !== "exchanging") return yield* connectError("InvalidAttempt", "Authorization attempt is no longer available.");
|
|
213
|
+
const requested = yield* store.get("OAuthConnection", attempt.connectionId);
|
|
214
|
+
const reusable = (requested ? [] : yield* store.load("OAuthConnection", { where: and(eq(field("application"), attempt.application), eq(field("userId"), tokens.userId)) })).find((row) => Object.entries(extra).every(([name, value]) => JSON.stringify(row[name]) === JSON.stringify(value)));
|
|
215
|
+
const connectionId = requested?.id ?? reusable?.id ?? attempt.connectionId;
|
|
216
|
+
const current = yield* store.get("OAuthConnection", connectionId);
|
|
217
|
+
if (current) {
|
|
218
|
+
if (current.application !== attempt.application) return yield* connectError("Forbidden", "Connection belongs to another application.");
|
|
219
|
+
}
|
|
220
|
+
const next = yield* saveTokens({
|
|
221
|
+
...extra,
|
|
222
|
+
...current,
|
|
223
|
+
id: connectionId,
|
|
224
|
+
application: attempt.application,
|
|
225
|
+
title: current?.title ?? application.title,
|
|
226
|
+
status: "active"
|
|
227
|
+
}, tokens);
|
|
228
|
+
const latestConnector = yield* store.get("OAuthApplication", application.id);
|
|
229
|
+
if (!latestConnector) return yield* connectError("NotFound", "OAuth application is unavailable.");
|
|
230
|
+
yield* store.put("OAuthApplication", {
|
|
231
|
+
...latestConnector,
|
|
232
|
+
connection: next.id
|
|
233
|
+
});
|
|
234
|
+
yield* store.put("OAuthAuthorizationAttempt", {
|
|
235
|
+
...attempt,
|
|
236
|
+
connectionId: next.id,
|
|
237
|
+
status: "completed"
|
|
238
|
+
});
|
|
239
|
+
yield* evict(attempt.codeVerifier);
|
|
240
|
+
return next;
|
|
241
|
+
}));
|
|
242
|
+
}).pipe(Effect.timeout(45e3), Effect.catchTag("TimeoutError", () => Effect.fail(connectError("Provider", "Authorization exchange timed out; start again.")))).pipe(Effect.catch((error) => Effect.andThen(store.transaction(Effect.gen(function* () {
|
|
243
|
+
const claimed = yield* store.get("OAuthAuthorizationAttempt", id);
|
|
244
|
+
if (!claimed || claimed.status !== "exchanging") return;
|
|
245
|
+
yield* store.put("OAuthAuthorizationAttempt", {
|
|
246
|
+
...attempt,
|
|
247
|
+
status: "failed"
|
|
248
|
+
});
|
|
249
|
+
yield* evict(attempt.codeVerifier);
|
|
250
|
+
})), Effect.fail(error))));
|
|
251
|
+
}),
|
|
252
|
+
clientCredentials: Effect.fn("Connect.clientCredentials")(function* (input) {
|
|
253
|
+
const { application } = yield* configured(input.applicationId);
|
|
254
|
+
if (application.flow !== "client-credentials") return yield* connectError("Configuration", "This application does not use client credentials.");
|
|
255
|
+
const connectionId = input.connectionId ?? application.connection ?? crypto.randomUUID();
|
|
256
|
+
yield* store.transaction(Effect.gen(function* () {
|
|
257
|
+
const existing = yield* store.get("OAuthConnection", connectionId);
|
|
258
|
+
if (existing && existing.application !== application.id) return yield* connectError("Forbidden", "Connection belongs to another application.");
|
|
259
|
+
if (existing) yield* busy(existing);
|
|
260
|
+
yield* store.put("OAuthConnection", {
|
|
261
|
+
...input.properties,
|
|
262
|
+
...existing,
|
|
263
|
+
id: connectionId,
|
|
264
|
+
title: existing?.title ?? application.title,
|
|
265
|
+
application: application.id,
|
|
266
|
+
status: "active"
|
|
267
|
+
});
|
|
268
|
+
const latest = yield* store.get("OAuthApplication", application.id);
|
|
269
|
+
if (!latest) return yield* connectError("NotFound", "OAuth application is unavailable.");
|
|
270
|
+
yield* store.put("OAuthApplication", {
|
|
271
|
+
...latest,
|
|
272
|
+
connection: connectionId
|
|
273
|
+
});
|
|
274
|
+
}));
|
|
275
|
+
return yield* refresh(connectionId);
|
|
276
|
+
}),
|
|
277
|
+
refresh,
|
|
278
|
+
disconnect: Effect.fn("Connect.disconnect")(function* (id) {
|
|
279
|
+
const record = yield* store.transaction(Effect.gen(function* () {
|
|
280
|
+
const current = yield* read(id);
|
|
281
|
+
const token = current.refreshToken ?? current.accessToken;
|
|
282
|
+
const plaintext = token ? yield* decrypt(token).pipe(Effect.catch(() => Effect.succeed(void 0))) : void 0;
|
|
283
|
+
yield* store.put("OAuthConnection", {
|
|
284
|
+
...current,
|
|
285
|
+
status: "inactive",
|
|
286
|
+
operationId: void 0,
|
|
287
|
+
operationExpiresAt: void 0,
|
|
288
|
+
accessToken: void 0,
|
|
289
|
+
accessTokenExpiresAt: void 0,
|
|
290
|
+
refreshToken: void 0,
|
|
291
|
+
refreshTokenExpiresAt: void 0
|
|
292
|
+
});
|
|
293
|
+
yield* evict(current.accessToken);
|
|
294
|
+
yield* evict(current.refreshToken);
|
|
295
|
+
return {
|
|
296
|
+
current,
|
|
297
|
+
plaintext
|
|
298
|
+
};
|
|
299
|
+
}));
|
|
300
|
+
if (record.plaintext) {
|
|
301
|
+
const { oauth } = yield* configured(record.current.application);
|
|
302
|
+
if (oauth.revoke) yield* oauth.revoke(Redacted.value(record.plaintext));
|
|
303
|
+
}
|
|
304
|
+
}),
|
|
305
|
+
forget: Effect.fn("Connect.forget")(function* (id) {
|
|
306
|
+
const removed = yield* store.transaction(Effect.gen(function* () {
|
|
307
|
+
const current = yield* store.get("OAuthConnection", id);
|
|
308
|
+
const token = current?.refreshToken ?? current?.accessToken;
|
|
309
|
+
const plaintext = token ? yield* decrypt(token).pipe(Effect.catch(() => Effect.succeed(void 0))) : void 0;
|
|
310
|
+
const attempts = yield* store.load("OAuthAuthorizationAttempt", { where: eq(field("connectionId"), id) });
|
|
311
|
+
for (const attempt of attempts) {
|
|
312
|
+
yield* evict(attempt.codeVerifier);
|
|
313
|
+
yield* store.delete("OAuthAuthorizationAttempt", attempt.id);
|
|
314
|
+
}
|
|
315
|
+
const applications = yield* store.load("OAuthApplication", { where: eq(field("connection"), id) });
|
|
316
|
+
for (const application of applications) yield* store.put("OAuthApplication", {
|
|
317
|
+
...application,
|
|
318
|
+
connection: void 0
|
|
319
|
+
});
|
|
320
|
+
if (current) {
|
|
321
|
+
yield* evict(current.accessToken);
|
|
322
|
+
yield* evict(current.refreshToken);
|
|
323
|
+
yield* store.delete("OAuthConnection", id);
|
|
324
|
+
}
|
|
325
|
+
return {
|
|
326
|
+
current,
|
|
327
|
+
plaintext
|
|
328
|
+
};
|
|
329
|
+
}));
|
|
330
|
+
if (removed.current && removed.plaintext) {
|
|
331
|
+
const { oauth } = yield* configured(removed.current.application);
|
|
332
|
+
if (oauth.revoke) yield* oauth.revoke(Redacted.value(removed.plaintext));
|
|
333
|
+
}
|
|
334
|
+
}),
|
|
335
|
+
collectExpired: Effect.fn("Connect.collectExpired")(function* ({ limit = 100 } = {}) {
|
|
336
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e3) return yield* connectError("Configuration", "GC batch size must be between 1 and 1000.");
|
|
337
|
+
return yield* store.transaction(Effect.gen(function* () {
|
|
338
|
+
const now = instant(yield* Clock.currentTimeMillis);
|
|
339
|
+
const attempts = yield* store.load("OAuthAuthorizationAttempt", {
|
|
340
|
+
where: lte(field("expiresAt"), now),
|
|
341
|
+
orderBy: [{ field: field("expiresAt") }],
|
|
342
|
+
limit
|
|
343
|
+
});
|
|
344
|
+
for (const attempt of attempts) {
|
|
345
|
+
yield* evict(attempt.codeVerifier);
|
|
346
|
+
yield* store.delete("OAuthAuthorizationAttempt", attempt.id);
|
|
347
|
+
}
|
|
348
|
+
const connections = yield* store.load("OAuthConnection", {
|
|
349
|
+
where: and(ne(field("refreshTokenExpiresAt"), void 0), lte(field("refreshTokenExpiresAt"), now), eq(field("operationId"), void 0)),
|
|
350
|
+
orderBy: [{ field: field("refreshTokenExpiresAt") }],
|
|
351
|
+
limit
|
|
352
|
+
});
|
|
353
|
+
for (const record of connections) {
|
|
354
|
+
yield* evict(record.refreshToken);
|
|
355
|
+
yield* store.put("OAuthConnection", {
|
|
356
|
+
...record,
|
|
357
|
+
refreshToken: void 0,
|
|
358
|
+
refreshTokenExpiresAt: void 0,
|
|
359
|
+
status: "needs-auth"
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
const expiredConnections = yield* store.load("ApiKeyConnection", {
|
|
363
|
+
where: and(eq(field("status"), "active"), ne(field("expiresAt"), void 0), lte(field("expiresAt"), now)),
|
|
364
|
+
orderBy: [{ field: field("expiresAt") }],
|
|
365
|
+
limit
|
|
366
|
+
});
|
|
367
|
+
for (const record of expiredConnections) yield* store.put("ApiKeyConnection", {
|
|
368
|
+
...record,
|
|
369
|
+
status: "needs-auth"
|
|
370
|
+
});
|
|
371
|
+
return {
|
|
372
|
+
attempts: attempts.length,
|
|
373
|
+
refreshTokens: connections.length
|
|
374
|
+
};
|
|
375
|
+
}));
|
|
376
|
+
})
|
|
377
|
+
});
|
|
378
|
+
});
|
|
379
|
+
//#endregion
|
|
380
|
+
export { OAuthAuthority, makeOAuthAuthority };
|
|
381
|
+
|
|
382
|
+
//# sourceMappingURL=oauthAuthority.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauthAuthority.js","names":[],"sources":["../../src/core/oauthAuthority.ts"],"sourcesContent":["import { and, eq, field, lte, ne } from \"@party-stack/ontology-storage\";\nimport { Clock, Context, Effect, Layer, Schema, Redacted } from \"effect\";\nimport * as oauth4webapi from \"oauth4webapi\";\nimport { Temporal } from \"temporal-polyfill\";\nimport { connectError, type ConnectError } from \"./errors.js\";\nimport type {\n ServiceInstanceRecord,\n OAuthAuthorizationAttemptRecord,\n OAuthConnectionRecord,\n OAuthApplicationRecord,\n} from \"../spec/index.js\";\nimport type { ConnectStore } from \"./store.js\";\nimport type { Encrypted } from \"@party-stack/ontology-spec/values\";\n\nexport interface OAuthTokens {\n accessToken: string;\n accessTokenExpiresAt?: Temporal.Instant;\n refreshToken?: string;\n refreshTokenExpiresAt?: Temporal.Instant;\n grantedScopes?: string;\n userId: string;\n}\nexport interface ConnectOAuthService {\n authorizationUrl(input: {\n state: string;\n codeChallenge: string;\n redirectUrl: string;\n }): Effect.Effect<string, ConnectError>;\n exchange(input: {\n callbackUrl: string;\n state: string;\n codeVerifier: string;\n redirectUrl: string;\n }): Effect.Effect<OAuthTokens, ConnectError>;\n refresh(refreshToken: string): Effect.Effect<OAuthTokens, ConnectError>;\n clientCredentials: Effect.Effect<OAuthTokens, ConnectError>;\n revoke?(token: string): Effect.Effect<void, ConnectError>;\n}\nexport interface BeginAuthorization {\n applicationId: string;\n principalId?: string;\n redirectUrl: string;\n returnUrl?: string;\n connectionId?: string;\n /** Trusted application fields; reserved attempt fields always take precedence. */\n properties?: Record<string, unknown>;\n}\nexport interface OAuthAuthorityService {\n connectionForApplication(\n applicationId: string\n ): Effect.Effect<OAuthConnectionRecord | undefined, ConnectError>;\n begin(input: BeginAuthorization): Effect.Effect<{ id: string; authorizationUrl: string }, ConnectError>;\n complete(input: {\n callbackUrl: string;\n principalId?: string;\n }): Effect.Effect<OAuthConnectionRecord, ConnectError>;\n clientCredentials(input: {\n applicationId: string;\n connectionId?: string;\n properties?: Record<string, unknown>;\n }): Effect.Effect<OAuthConnectionRecord, ConnectError>;\n refresh(connectionId: string): Effect.Effect<OAuthConnectionRecord, ConnectError>;\n disconnect(connectionId: string): Effect.Effect<void, ConnectError>;\n forget(connectionId: string): Effect.Effect<void, ConnectError>;\n /** Indexed, bounded maintenance. Does not delete connection identities. */\n collectExpired(options?: {\n limit?: number;\n }): Effect.Effect<{ attempts: number; refreshTokens: number }, ConnectError>;\n}\nexport interface ConnectCredentialValues {\n encrypt<A, AI>(schema: Schema.Codec<A, AI>, value: A): Effect.Effect<Encrypted<A>, unknown>;\n decrypt<A, AI>(schema: Schema.Codec<A, AI>, value: Encrypted<A>): Effect.Effect<A, unknown>;\n evict(value: Encrypted<unknown>): Effect.Effect<void, unknown>;\n}\nexport interface OAuthAuthorityOptions {\n store: ConnectStore;\n values: ConnectCredentialValues;\n oauth(input: {\n application: OAuthApplicationRecord;\n serviceInstance: ServiceInstanceRecord;\n }): Effect.Effect<ConnectOAuthService, ConnectError>;\n /** Populate application ownership properties in the same commit as token storage. */\n connectionProperties?(\n attempt: OAuthAuthorizationAttemptRecord\n ): Effect.Effect<Record<string, unknown>, ConnectError>;\n}\nexport class OAuthAuthority extends Context.Service<OAuthAuthority, OAuthAuthorityService>()(\n \"@party-stack/connect/OAuthAuthority\"\n) {\n static readonly layer = (options: OAuthAuthorityOptions) =>\n Layer.effect(OAuthAuthority, makeOAuthAuthority(options));\n}\nconst instant = (milliseconds: number) => Temporal.Instant.fromEpochMilliseconds(milliseconds);\nconst expired = (time: Temporal.Instant | undefined, now: number) =>\n time !== undefined && time.epochMilliseconds <= now;\nconst guardUrl = (value: string) =>\n Effect.try({\n try: () => {\n const url = new URL(value);\n if (\n url.protocol !== \"https:\" &&\n !(url.protocol === \"http:\" && [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname))\n )\n throw new Error();\n return url;\n },\n catch: () => connectError(\"Configuration\", \"OAuth URLs require HTTPS (or HTTP on localhost).\"),\n });\n\n/** One credential authority, usable by both device and HTTP entry points. */\nexport const makeOAuthAuthority = (options: OAuthAuthorityOptions): Effect.Effect<OAuthAuthorityService> =>\n Effect.sync(() => {\n const { store, values } = options;\n const read = Effect.fnUntraced(function* (id: string) {\n const record = yield* store.get(\"OAuthConnection\", id);\n if (!record) return yield* connectError(\"NotFound\", \"Connection is unavailable.\");\n return record;\n });\n const configured = Effect.fnUntraced(function* (id: string) {\n const application = yield* store.get(\"OAuthApplication\", id);\n if (!application) return yield* connectError(\"NotFound\", \"OAuth application is unavailable.\");\n const serviceInstance = yield* store.get(\"ServiceInstance\", application.serviceInstance);\n if (!serviceInstance) return yield* connectError(\"NotFound\", \"Service instance is unavailable.\");\n return { application, oauth: yield* options.oauth({ application, serviceInstance }) };\n });\n const decrypt = (value: Encrypted<string>) =>\n values.decrypt(Schema.String, value).pipe(\n Effect.map(Redacted.make),\n Effect.mapError(() => connectError(\"Storage\", \"Credential decryption failed.\"))\n );\n const encrypt = (value: string) =>\n values\n .encrypt(Schema.String, value)\n .pipe(Effect.mapError(() => connectError(\"Storage\", \"Credential encryption failed.\")));\n const evict = (value: Encrypted<string> | undefined) =>\n value\n ? values\n .evict(value)\n .pipe(\n Effect.mapError(() => connectError(\"Storage\", \"Credential deletion failed.\", true))\n )\n : Effect.void;\n const saveTokens = Effect.fnUntraced(function* (record: OAuthConnectionRecord, tokens: OAuthTokens) {\n if (record.userId && record.userId !== tokens.userId)\n return yield* connectError(\n \"NeedsAuthentication\",\n \"Provider identity changed; reconnect explicitly.\"\n );\n const next: OAuthConnectionRecord = {\n ...record,\n status: \"active\",\n userId: tokens.userId,\n accessToken: yield* encrypt(tokens.accessToken),\n accessTokenExpiresAt: tokens.accessTokenExpiresAt,\n refreshToken: tokens.refreshToken ? yield* encrypt(tokens.refreshToken) : undefined,\n refreshTokenExpiresAt: tokens.refreshToken ? tokens.refreshTokenExpiresAt : undefined,\n grantedScopes: tokens.grantedScopes,\n operationId: undefined,\n operationExpiresAt: undefined,\n };\n yield* store.put(\"OAuthConnection\", next);\n yield* evict(record.accessToken);\n yield* evict(record.refreshToken);\n return next;\n });\n const busy = Effect.fnUntraced(function* (record: OAuthConnectionRecord, recovery = false) {\n if (!record.operationId) return;\n const now = yield* Clock.currentTimeMillis;\n if (!expired(record.operationExpiresAt, now))\n return yield* connectError(\"Busy\", \"Connection operation is in progress.\", true);\n if (recovery) return;\n // A refresh may have rotated the token before its reply was lost. Never retry blindly.\n return yield* connectError(\n \"NeedsAuthentication\",\n \"An interrupted credential operation requires reconnection.\"\n );\n });\n const finish = Effect.fnUntraced(function* (record: OAuthConnectionRecord, id: string) {\n const current = yield* read(record.id);\n if (current.operationId !== id)\n return yield* connectError(\"Busy\", \"Connection changed during the credential operation.\");\n return current;\n });\n const refresh = Effect.fn(\"Connect.refresh\")(function* (connectionId: string) {\n const operationId = crypto.randomUUID();\n const record = yield* store.transaction(\n Effect.gen(function* () {\n const current = yield* read(connectionId);\n yield* busy(current);\n if (current.status !== \"active\")\n return yield* connectError(\"NeedsAuthentication\", \"Reconnect this connection.\");\n const next = {\n ...current,\n operationId,\n operationExpiresAt: instant((yield* Clock.currentTimeMillis) + 60_000),\n };\n yield* store.put(\"OAuthConnection\", next);\n return next;\n })\n );\n const request = Effect.gen(function* () {\n const { application, oauth } = yield* configured(record.application);\n let tokens: OAuthTokens;\n if (application.flow === \"client-credentials\") tokens = yield* oauth.clientCredentials;\n else {\n if (\n !record.refreshToken ||\n expired(record.refreshTokenExpiresAt, yield* Clock.currentTimeMillis)\n )\n return yield* connectError(\n \"NeedsAuthentication\",\n \"Refresh credentials are unavailable or expired.\"\n );\n tokens = yield* oauth.refresh(Redacted.value(yield* decrypt(record.refreshToken)));\n if (!tokens.refreshToken)\n tokens = {\n ...tokens,\n refreshToken: Redacted.value(yield* decrypt(record.refreshToken)),\n refreshTokenExpiresAt: record.refreshTokenExpiresAt,\n };\n }\n return yield* store.transaction(\n Effect.gen(function* () {\n const current = yield* finish(record, operationId);\n return yield* saveTokens(current, tokens);\n })\n );\n }).pipe(\n Effect.timeout(45_000),\n Effect.catchTag(\"TimeoutError\", () =>\n Effect.fail(\n connectError(\n \"NeedsAuthentication\",\n \"Credential exchange timed out; reconnect before retrying.\"\n )\n )\n )\n );\n return yield* request.pipe(\n Effect.catch((error) =>\n store\n .transaction(\n Effect.gen(function* () {\n const current = yield* finish(record, operationId);\n if (error.kind === \"NeedsAuthentication\") {\n yield* evict(current.refreshToken);\n yield* store.put(\"OAuthConnection\", {\n ...current,\n refreshToken: undefined,\n refreshTokenExpiresAt: undefined,\n status: \"needs-auth\",\n operationId: undefined,\n operationExpiresAt: undefined,\n });\n } else if (error.kind !== \"Storage\")\n yield* store.put(\"OAuthConnection\", {\n ...current,\n operationId: undefined,\n operationExpiresAt: undefined,\n });\n })\n )\n .pipe(Effect.andThen(Effect.fail(error)))\n )\n );\n });\n return OAuthAuthority.of({\n connectionForApplication: Effect.fn(\"Connect.connectionForApplication\")(function* (\n applicationId: string\n ) {\n const application = yield* store.get(\"OAuthApplication\", applicationId);\n if (!application) return yield* connectError(\"NotFound\", \"OAuth application is unavailable.\");\n if (!application.connection) return;\n const connection = yield* read(application.connection);\n if (connection.application !== applicationId)\n return yield* connectError(\n \"Configuration\",\n \"OAuth application points to a connection belonging to another application.\"\n );\n return connection;\n }),\n begin: Effect.fn(\"Connect.begin\")(function* (input: BeginAuthorization) {\n yield* guardUrl(input.redirectUrl);\n if (input.returnUrl) yield* guardUrl(input.returnUrl);\n const { application, oauth } = yield* configured(input.applicationId);\n if (application.redirectUrl && input.redirectUrl !== application.redirectUrl)\n return yield* connectError(\n \"Forbidden\",\n \"Redirect URL does not match the OAuth application.\"\n );\n if (application.flow !== \"authorization-code\")\n return yield* connectError(\n \"Configuration\",\n \"This application does not support interactive authorization.\"\n );\n const id = oauth4webapi.generateRandomState();\n const verifier = oauth4webapi.generateRandomCodeVerifier();\n const challenge = yield* Effect.tryPromise({\n try: () => oauth4webapi.calculatePKCECodeChallenge(verifier),\n catch: () => connectError(\"Configuration\", \"Could not generate PKCE challenge.\"),\n });\n const authorizationUrl = yield* oauth.authorizationUrl({\n state: id,\n codeChallenge: challenge,\n redirectUrl: input.redirectUrl,\n });\n yield* guardUrl(authorizationUrl);\n yield* store.transaction(\n Effect.gen(function* () {\n if (input.connectionId) {\n const previous = yield* read(input.connectionId);\n if (previous.application !== input.applicationId)\n return yield* connectError(\n \"Forbidden\",\n \"Connection belongs to another application.\"\n );\n yield* busy(previous, true);\n }\n yield* store.put(\"OAuthAuthorizationAttempt\", {\n ...input.properties,\n id,\n application: input.applicationId,\n principalId: input.principalId,\n connectionId: input.connectionId ?? crypto.randomUUID(),\n redirectUrl: input.redirectUrl,\n returnUrl: input.returnUrl,\n codeVerifier: yield* encrypt(verifier),\n expiresAt: instant((yield* Clock.currentTimeMillis) + 600_000),\n status: \"pending\",\n });\n })\n );\n return { id, authorizationUrl };\n }),\n complete: Effect.fn(\"Connect.complete\")(function* (input: {\n callbackUrl: string;\n principalId?: string;\n }) {\n const callback = yield* guardUrl(input.callbackUrl);\n const id = callback.searchParams.get(\"state\");\n if (!id)\n return yield* connectError(\"InvalidAttempt\", \"Authorization attempt is unavailable.\");\n const attempt = yield* store.transaction(\n Effect.gen(function* () {\n const current = yield* store.get(\"OAuthAuthorizationAttempt\", id);\n if (\n !current ||\n current.principalId !== input.principalId ||\n expired(current.expiresAt, yield* Clock.currentTimeMillis)\n )\n return yield* connectError(\n \"InvalidAttempt\",\n \"Authorization attempt is unavailable.\"\n );\n const expected = new URL(current.redirectUrl);\n if (expected.origin !== callback.origin || expected.pathname !== callback.pathname)\n return yield* connectError(\n \"InvalidAttempt\",\n \"Authorization callback URL does not match.\"\n );\n if (current.status === \"completed\") return current;\n if (current.status !== \"pending\")\n return yield* connectError(\n \"InvalidAttempt\",\n \"Authorization attempt was already consumed; start again.\"\n );\n yield* store.put(\"OAuthAuthorizationAttempt\", { ...current, status: \"exchanging\" });\n return current;\n })\n );\n if (attempt.status === \"completed\") {\n if (!attempt.connectionId)\n return yield* connectError(\n \"InvalidAttempt\",\n \"Completed authorization has no connection.\"\n );\n return yield* read(attempt.connectionId);\n }\n const exchange = Effect.gen(function* () {\n const { application, oauth } = yield* configured(attempt.application);\n const tokens = yield* oauth.exchange({\n callbackUrl: input.callbackUrl,\n state: id,\n redirectUrl: attempt.redirectUrl,\n codeVerifier: Redacted.value(yield* decrypt(attempt.codeVerifier)),\n });\n const extra = options.connectionProperties\n ? yield* options.connectionProperties(attempt)\n : {};\n return yield* store.transaction(\n Effect.gen(function* () {\n const claimed = yield* store.get(\"OAuthAuthorizationAttempt\", id);\n if (!claimed || claimed.status !== \"exchanging\")\n return yield* connectError(\n \"InvalidAttempt\",\n \"Authorization attempt is no longer available.\"\n );\n const requested = yield* store.get(\"OAuthConnection\", attempt.connectionId);\n const matches = requested\n ? []\n : yield* store.load(\"OAuthConnection\", {\n where: and(\n eq(field(\"application\"), attempt.application),\n eq(field(\"userId\"), tokens.userId)\n ),\n });\n // Trusted application ownership fields participate in reuse;\n // two projects/principals can still keep separate bindings.\n const reusable = matches.find((row) =>\n Object.entries(extra).every(\n ([name, value]) =>\n JSON.stringify((row as Record<string, unknown>)[name]) ===\n JSON.stringify(value)\n )\n );\n const connectionId = requested?.id ?? reusable?.id ?? attempt.connectionId;\n const current = yield* store.get(\"OAuthConnection\", connectionId);\n if (current) {\n if (current.application !== attempt.application)\n return yield* connectError(\n \"Forbidden\",\n \"Connection belongs to another application.\"\n );\n }\n // A completed login supersedes an in-flight refresh. Clearing\n // operationId fences its late result in finish().\n const next = yield* saveTokens(\n {\n ...extra,\n ...current,\n id: connectionId,\n application: attempt.application,\n title: current?.title ?? application.title,\n status: \"active\",\n },\n tokens\n );\n const latestConnector = yield* store.get(\"OAuthApplication\", application.id);\n if (!latestConnector)\n return yield* connectError(\"NotFound\", \"OAuth application is unavailable.\");\n yield* store.put(\"OAuthApplication\", { ...latestConnector, connection: next.id });\n yield* store.put(\"OAuthAuthorizationAttempt\", {\n ...attempt,\n connectionId: next.id,\n status: \"completed\",\n });\n yield* evict(attempt.codeVerifier);\n return next;\n })\n );\n }).pipe(\n Effect.timeout(45_000),\n Effect.catchTag(\"TimeoutError\", () =>\n Effect.fail(\n connectError(\"Provider\", \"Authorization exchange timed out; start again.\")\n )\n )\n );\n return yield* exchange.pipe(\n Effect.catch((error) =>\n Effect.andThen(\n store.transaction(\n Effect.gen(function* () {\n const claimed = yield* store.get(\"OAuthAuthorizationAttempt\", id);\n if (!claimed || claimed.status !== \"exchanging\") return;\n yield* store.put(\"OAuthAuthorizationAttempt\", {\n ...attempt,\n status: \"failed\",\n });\n yield* evict(attempt.codeVerifier);\n })\n ),\n Effect.fail(error)\n )\n )\n );\n }),\n clientCredentials: Effect.fn(\"Connect.clientCredentials\")(function* (input: {\n applicationId: string;\n connectionId?: string;\n properties?: Record<string, unknown>;\n }) {\n const { application } = yield* configured(input.applicationId);\n if (application.flow !== \"client-credentials\")\n return yield* connectError(\n \"Configuration\",\n \"This application does not use client credentials.\"\n );\n const connectionId = input.connectionId ?? application.connection ?? crypto.randomUUID();\n yield* store.transaction(\n Effect.gen(function* () {\n const existing = yield* store.get(\"OAuthConnection\", connectionId);\n if (existing && existing.application !== application.id)\n return yield* connectError(\n \"Forbidden\",\n \"Connection belongs to another application.\"\n );\n if (existing) yield* busy(existing);\n yield* store.put(\"OAuthConnection\", {\n ...input.properties,\n ...existing,\n id: connectionId,\n title: existing?.title ?? application.title,\n application: application.id,\n status: \"active\",\n });\n const latest = yield* store.get(\"OAuthApplication\", application.id);\n if (!latest)\n return yield* connectError(\"NotFound\", \"OAuth application is unavailable.\");\n yield* store.put(\"OAuthApplication\", { ...latest, connection: connectionId });\n })\n );\n return yield* refresh(connectionId);\n }),\n refresh,\n disconnect: Effect.fn(\"Connect.disconnect\")(function* (id: string) {\n // Detach credentials atomically first. Revocation failure must not restore local access.\n const record = yield* store.transaction(\n Effect.gen(function* () {\n const current = yield* read(id);\n const token = current.refreshToken ?? current.accessToken;\n const plaintext = token\n ? yield* decrypt(token).pipe(Effect.catch(() => Effect.succeed(undefined)))\n : undefined;\n yield* store.put(\"OAuthConnection\", {\n ...current,\n status: \"inactive\",\n operationId: undefined,\n operationExpiresAt: undefined,\n accessToken: undefined,\n accessTokenExpiresAt: undefined,\n refreshToken: undefined,\n refreshTokenExpiresAt: undefined,\n });\n yield* evict(current.accessToken);\n yield* evict(current.refreshToken);\n return { current, plaintext };\n })\n );\n if (record.plaintext) {\n const { oauth } = yield* configured(record.current.application);\n if (oauth.revoke) yield* oauth.revoke(Redacted.value(record.plaintext));\n }\n }),\n forget: Effect.fn(\"Connect.forget\")(function* (id: string) {\n const removed = yield* store.transaction(\n Effect.gen(function* () {\n const current = yield* store.get(\"OAuthConnection\", id);\n const token = current?.refreshToken ?? current?.accessToken;\n const plaintext = token\n ? yield* decrypt(token).pipe(Effect.catch(() => Effect.succeed(undefined)))\n : undefined;\n const attempts = yield* store.load(\"OAuthAuthorizationAttempt\", {\n where: eq(field(\"connectionId\"), id),\n });\n for (const attempt of attempts) {\n yield* evict(attempt.codeVerifier);\n yield* store.delete(\"OAuthAuthorizationAttempt\", attempt.id);\n }\n const applications = yield* store.load(\"OAuthApplication\", {\n where: eq(field(\"connection\"), id),\n });\n for (const application of applications)\n yield* store.put(\"OAuthApplication\", { ...application, connection: undefined });\n if (current) {\n yield* evict(current.accessToken);\n yield* evict(current.refreshToken);\n yield* store.delete(\"OAuthConnection\", id);\n }\n return { current, plaintext };\n })\n );\n // Local deletion commits before remote revocation, including when\n // revocation fails. Action reference validation remains at the boundary.\n if (removed.current && removed.plaintext) {\n const { oauth } = yield* configured(removed.current.application);\n if (oauth.revoke) yield* oauth.revoke(Redacted.value(removed.plaintext));\n }\n }),\n collectExpired: Effect.fn(\"Connect.collectExpired\")(function* ({\n limit = 100,\n }: { limit?: number } = {}) {\n if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1000)\n return yield* connectError(\"Configuration\", \"GC batch size must be between 1 and 1000.\");\n return yield* store.transaction(\n Effect.gen(function* () {\n const now = instant(yield* Clock.currentTimeMillis);\n const attempts = yield* store.load(\"OAuthAuthorizationAttempt\", {\n where: lte(field(\"expiresAt\"), now),\n orderBy: [{ field: field(\"expiresAt\") }],\n limit,\n });\n for (const attempt of attempts) {\n yield* evict(attempt.codeVerifier);\n yield* store.delete(\"OAuthAuthorizationAttempt\", attempt.id);\n }\n const connections = yield* store.load(\"OAuthConnection\", {\n where: and(\n ne(field(\"refreshTokenExpiresAt\"), undefined),\n lte(field(\"refreshTokenExpiresAt\"), now),\n eq(field(\"operationId\"), undefined)\n ),\n orderBy: [{ field: field(\"refreshTokenExpiresAt\") }],\n limit,\n });\n for (const record of connections) {\n yield* evict(record.refreshToken);\n yield* store.put(\"OAuthConnection\", {\n ...record,\n refreshToken: undefined,\n refreshTokenExpiresAt: undefined,\n status: \"needs-auth\",\n });\n }\n // External sessions can be extended upstream. Revalidate\n // them on demand instead of declaring a cached expiry final.\n const expiredConnections = yield* store.load(\"ApiKeyConnection\", {\n where: and(\n eq(field(\"status\"), \"active\"),\n ne(field(\"expiresAt\"), undefined),\n lte(field(\"expiresAt\"), now)\n ),\n orderBy: [{ field: field(\"expiresAt\") }],\n limit,\n });\n for (const record of expiredConnections)\n yield* store.put(\"ApiKeyConnection\", { ...record, status: \"needs-auth\" });\n return { attempts: attempts.length, refreshTokens: connections.length };\n })\n );\n }),\n });\n });\n"],"mappings":";;;;;;AAsFA,IAAa,iBAAb,MAAa,uBAAuB,QAAQ,QAA+C,CAAC,CACxF,qCACJ,CAAC,CAAC;CACE,OAAgB,SAAS,YACrB,MAAM,OAAO,gBAAgB,mBAAmB,OAAO,CAAC;AAChE;AACA,MAAM,WAAW,iBAAyB,SAAS,QAAQ,sBAAsB,YAAY;AAC7F,MAAM,WAAW,MAAoC,QACjD,SAAS,KAAA,KAAa,KAAK,qBAAqB;AACpD,MAAM,YAAY,UACd,OAAO,IAAI;CACP,WAAW;EACP,MAAM,MAAM,IAAI,IAAI,KAAK;EACzB,IACI,IAAI,aAAa,YACjB,EAAE,IAAI,aAAa,WAAW;GAAC;GAAa;GAAa;EAAO,CAAC,CAAC,SAAS,IAAI,QAAQ,IAEvF,MAAM,IAAI,MAAM;EACpB,OAAO;CACX;CACA,aAAa,aAAa,iBAAiB,kDAAkD;AACjG,CAAC;;AAGL,MAAa,sBAAsB,YAC/B,OAAO,WAAW;CACd,MAAM,EAAE,OAAO,WAAW;CAC1B,MAAM,OAAO,OAAO,WAAW,WAAW,IAAY;EAClD,MAAM,SAAS,OAAO,MAAM,IAAI,mBAAmB,EAAE;EACrD,IAAI,CAAC,QAAQ,OAAO,OAAO,aAAa,YAAY,4BAA4B;EAChF,OAAO;CACX,CAAC;CACD,MAAM,aAAa,OAAO,WAAW,WAAW,IAAY;EACxD,MAAM,cAAc,OAAO,MAAM,IAAI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AAO,IACH,GAAG,MAAM,uBAAuB,GAAG,KAAA,CAAS,GAC5C,IAAI,MAAM,uBAAuB,GAAG,GAAG,GACvC,GAAG,MAAM,aAAa,GAAG,KAAA,CAAS,CACtC;KACA,SAAS,CAAC,EAAE,OAAO,MAAM,uBAAuB,EAAE,CAAC;KACnD;IACJ,CAAC;IACD,KAAK,MAAM,UAAU,aAAa;KAC9B,OAAO,MAAM,OAAO,YAAY;KAChC,OAAO,MAAM,IAAI,mBAAmB;MAChC,GAAG;MACH,cAAc,KAAA;MACd,uBAAuB,KAAA;MACvB,QAAQ;KACZ,CAAC;IACL;IAGA,MAAM,qBAAqB,OAAO,MAAM,KAAK,oBAAoB;KAC7D,OAAO,IACH,GAAG,MAAM,QAAQ,GAAG,QAAQ,GAC5B,GAAG,MAAM,WAAW,GAAG,KAAA,CAAS,GAChC,IAAI,MAAM,WAAW,GAAG,GAAG,CAC/B;KACA,SAAS,CAAC,EAAE,OAAO,MAAM,WAAW,EAAE,CAAC;KACvC;IACJ,CAAC;IACD,KAAK,MAAM,UAAU,oBACjB,OAAO,MAAM,IAAI,oBAAoB;KAAE,GAAG;KAAQ,QAAQ;IAAa,CAAC;IAC5E,OAAO;KAAE,UAAU,SAAS;KAAQ,eAAe,YAAY;IAAO;GAC1E,CAAC,CACL;EACJ,CAAC;CACL,CAAC;AACL,CAAC"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { ConnectError } from "./errors.js";
|
|
2
|
+
import { ApiKeyConnectionRecord, ExternalSessionConnectionRecord, OAuthApplicationRecord, OAuthAuthorizationAttemptRecord, OAuthConnectionRecord, ServiceInstanceRecord } from "../spec/index.js";
|
|
3
|
+
import { Query } from "@party-stack/ontology-storage";
|
|
4
|
+
import { Effect } from "effect";
|
|
5
|
+
import { OntologyIR } from "@party-stack/ontology-spec";
|
|
6
|
+
import { TablesService } from "@party-stack/ontology-storage/tables";
|
|
7
|
+
//#region src/core/store.d.ts
|
|
8
|
+
type Records = {
|
|
9
|
+
ServiceInstance: ServiceInstanceRecord;
|
|
10
|
+
OAuthApplication: OAuthApplicationRecord;
|
|
11
|
+
OAuthConnection: OAuthConnectionRecord;
|
|
12
|
+
OAuthAuthorizationAttempt: OAuthAuthorizationAttemptRecord;
|
|
13
|
+
ApiKeyConnection: ApiKeyConnectionRecord;
|
|
14
|
+
ExternalSessionConnection: ExternalSessionConnectionRecord;
|
|
15
|
+
};
|
|
16
|
+
/** Remote implementations may implement this boundary with trusted ontology actions.
|
|
17
|
+
* transaction must atomically enforce the read/write decisions in its body.
|
|
18
|
+
*/
|
|
19
|
+
export interface ConnectStore {
|
|
20
|
+
get<N extends keyof Records>(name: N, id: string): Effect.Effect<Records[N] | undefined, ConnectError>;
|
|
21
|
+
put<N extends keyof Records>(name: N, value: Records[N]): Effect.Effect<void, ConnectError>;
|
|
22
|
+
delete<N extends keyof Records>(name: N, id: string): Effect.Effect<void, ConnectError>;
|
|
23
|
+
load<N extends keyof Records>(name: N, query: Query): Effect.Effect<Records[N][], ConnectError>;
|
|
24
|
+
transaction<A, E, R>(body: Effect.Effect<A, E, R>): Effect.Effect<A, E | ConnectError, R>;
|
|
25
|
+
}
|
|
26
|
+
/** Additional application properties are validated and preserved by the compiled ontology. */
|
|
27
|
+
export declare const makeConnectPersistence: (options: {
|
|
28
|
+
tables: TablesService;
|
|
29
|
+
namespace: string;
|
|
30
|
+
ir?: OntologyIR;
|
|
31
|
+
maintenance?: false | {
|
|
32
|
+
readonly intervalMs?: number;
|
|
33
|
+
};
|
|
34
|
+
}) => Effect.Effect<{
|
|
35
|
+
store: ConnectStore;
|
|
36
|
+
backend: import("@party-stack/ontology-backend/owned").OwnedBackendService;
|
|
37
|
+
}, import("@party-stack/ontology-backend").BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced"> | ConnectError, import("effect/Scope").Scope>;
|
|
38
|
+
export declare const makeConnectStore: (options: {
|
|
39
|
+
tables: TablesService;
|
|
40
|
+
namespace: string;
|
|
41
|
+
ir?: OntologyIR;
|
|
42
|
+
maintenance?: false | {
|
|
43
|
+
readonly intervalMs?: number;
|
|
44
|
+
};
|
|
45
|
+
}) => Effect.Effect<ConnectStore, import("@party-stack/ontology-backend").BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced"> | ConnectError, import("effect/Scope").Scope>;
|
|
46
|
+
//#endregion
|
|
47
|
+
export {};
|
|
48
|
+
//# sourceMappingURL=store.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store.d.ts","names":[],"sources":["../../src/core/store.ts"],"mappings":";;;;;;;KAoBK;EACD,iBAAiB;EACjB,kBAAkB;EAClB,iBAAiB;EACjB,2BAA2B;EAC3B,kBAAkB;EAClB,2BAA2B;;;;;iBAKd;EACb,IAAI,gBAAgB,SAAS,MAAM,GAAG,aAAa,OAAO,OAAO,QAAQ,gBAAgB;EACzF,IAAI,gBAAgB,SAAS,MAAM,GAAG,OAAO,QAAQ,KAAK,OAAO,aAAa;EAC9E,OAAO,gBAAgB,SAAS,MAAM,GAAG,aAAa,OAAO,aAAa;EAC1E,KAAK,gBAAgB,SAAS,MAAM,GAAG,OAAO,QAAQ,OAAO,OAAO,QAAQ,MAAM;EAClF,YAAY,GAAG,GAAG,GAAG,MAAM,OAAO,OAAO,GAAG,GAAG,KAAK,OAAO,OAAO,GAAG,IAAI,cAAc;;;qBAI9E,yBAAsB;EACvB,QAAA;EACG;EACN,KAAA;EACS;aAAmB;;;;;2CA6FnC,kWAAA,qCAAA;qBAEW,mBAAgB;EAlGjB,QAAA;EACG;EACN,KAAA;EACS;aAAmB;;MAmGnC,OAAA,OAAA,sDAAA,kWAAA,qCAAA"}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { connectOntology } from "../spec/index.js";
|
|
2
|
+
import { connectError } from "./errors.js";
|
|
3
|
+
import { migrateConnectCredentials } from "./migrate.js";
|
|
4
|
+
import { field } from "@party-stack/ontology-storage";
|
|
5
|
+
import { Context, Effect } from "effect";
|
|
6
|
+
import { compileEffectSchemas } from "@party-stack/ontology-spec/effect";
|
|
7
|
+
import { makeOwnedBackend } from "@party-stack/ontology-backend/owned";
|
|
8
|
+
//#region src/core/store.ts
|
|
9
|
+
/** Additional application properties are validated and preserved by the compiled ontology. */
|
|
10
|
+
const makeConnectPersistence = Effect.fn("Connect.persistence")(function* (options) {
|
|
11
|
+
const ir = options.ir ?? connectOntology;
|
|
12
|
+
const protect = (effect) => effect.pipe(Effect.mapError(() => connectError("Storage", "Connect storage operation failed.", true)));
|
|
13
|
+
yield* Effect.try({
|
|
14
|
+
try: () => {
|
|
15
|
+
for (const base of connectOntology.objectTypes) {
|
|
16
|
+
const definition = ir.objectTypes.find((candidate) => candidate.name === base.name);
|
|
17
|
+
if (!definition || definition.primaryKey !== base.primaryKey) throw new Error();
|
|
18
|
+
for (const property of base.properties) {
|
|
19
|
+
const actual = definition.properties.find((candidate) => candidate.name === property.name);
|
|
20
|
+
if (!actual || JSON.stringify(actual.type) !== JSON.stringify(property.type)) throw new Error();
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
compileEffectSchemas(ir);
|
|
24
|
+
},
|
|
25
|
+
catch: () => connectError("Configuration", "Connect definitions must retain their standard properties and primary keys.")
|
|
26
|
+
});
|
|
27
|
+
const backend = yield* makeOwnedBackend({
|
|
28
|
+
...options,
|
|
29
|
+
namespace: JSON.stringify([
|
|
30
|
+
options.namespace,
|
|
31
|
+
"connect",
|
|
32
|
+
3
|
|
33
|
+
]),
|
|
34
|
+
ir,
|
|
35
|
+
mutators: {}
|
|
36
|
+
});
|
|
37
|
+
const CurrentTransaction = Context.Service(`Connect.transaction:${crypto.randomUUID()}`);
|
|
38
|
+
const inTransaction = (body) => Effect.serviceOption(CurrentTransaction).pipe(Effect.flatMap((current) => current._tag === "Some" ? body(current.value) : backend.storage.transaction(body)));
|
|
39
|
+
const read = (body) => Effect.serviceOption(CurrentTransaction).pipe(Effect.flatMap((current) => current._tag === "Some" ? body(current.value) : backend.storage.read(body)));
|
|
40
|
+
const store = {
|
|
41
|
+
get: (name, id) => protect(read((tx) => tx.get(name, id))).pipe(Effect.map((value) => value)),
|
|
42
|
+
put: (name, value) => protect(inTransaction((tx) => tx.put(name, value))),
|
|
43
|
+
delete: (name, id) => protect(inTransaction((tx) => tx.delete(name, id))),
|
|
44
|
+
load: (name, query) => protect(read((tx) => tx.loadSubset(name, query))).pipe(Effect.map((rows) => rows.map((row) => row.value))),
|
|
45
|
+
transaction: (body) => inTransaction((tx) => body.pipe(Effect.provideService(CurrentTransaction, tx))).pipe(Effect.catchTag("BackendError", () => Effect.fail(connectError("Storage", "Connect transaction failed.", true))))
|
|
46
|
+
};
|
|
47
|
+
for (const [name, fields] of Object.entries({
|
|
48
|
+
OAuthApplication: ["serviceInstance", "connection"],
|
|
49
|
+
OAuthConnection: [
|
|
50
|
+
"application",
|
|
51
|
+
"userId",
|
|
52
|
+
"accessTokenExpiresAt",
|
|
53
|
+
"refreshTokenExpiresAt",
|
|
54
|
+
"operationExpiresAt"
|
|
55
|
+
],
|
|
56
|
+
OAuthAuthorizationAttempt: [
|
|
57
|
+
"expiresAt",
|
|
58
|
+
"application",
|
|
59
|
+
"connectionId"
|
|
60
|
+
],
|
|
61
|
+
ApiKeyConnection: [
|
|
62
|
+
"serviceInstance",
|
|
63
|
+
"userId",
|
|
64
|
+
"expiresAt"
|
|
65
|
+
],
|
|
66
|
+
ExternalSessionConnection: [
|
|
67
|
+
"serviceInstance",
|
|
68
|
+
"userId",
|
|
69
|
+
"sessionId",
|
|
70
|
+
"expiresAt"
|
|
71
|
+
]
|
|
72
|
+
})) for (const property of fields) yield* protect(backend.storage.transaction((tx) => tx.ensureIndex(name, {
|
|
73
|
+
name: property,
|
|
74
|
+
field: field(property)
|
|
75
|
+
})));
|
|
76
|
+
yield* protect(migrateConnectCredentials({
|
|
77
|
+
...options,
|
|
78
|
+
ir,
|
|
79
|
+
store
|
|
80
|
+
}));
|
|
81
|
+
return {
|
|
82
|
+
store,
|
|
83
|
+
backend
|
|
84
|
+
};
|
|
85
|
+
});
|
|
86
|
+
const makeConnectStore = Effect.fn("Connect.store")(function* (options) {
|
|
87
|
+
return (yield* makeConnectPersistence(options)).store;
|
|
88
|
+
});
|
|
89
|
+
//#endregion
|
|
90
|
+
export { makeConnectPersistence, makeConnectStore };
|
|
91
|
+
|
|
92
|
+
//# sourceMappingURL=store.js.map
|