@party-stack/connect 0.3.3 → 0.4.0
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/core/accessToken.d.ts +16 -1
- package/lib/core/accessToken.d.ts.map +1 -1
- package/lib/core/accessToken.js +10 -4
- package/lib/core/accessToken.js.map +1 -1
- package/lib/core/oauthAuthority.d.ts +5 -0
- package/lib/core/oauthAuthority.d.ts.map +1 -1
- package/lib/core/oauthAuthority.js +30 -3
- package/lib/core/oauthAuthority.js.map +1 -1
- package/lib/index.d.ts +1 -2
- package/lib/index.js +1 -2
- package/lib/makeConnectManager.d.ts.map +1 -1
- package/lib/makeConnectManager.js +1 -0
- package/lib/makeConnectManager.js.map +1 -1
- package/lib/publicOntology.d.ts.map +1 -1
- package/lib/publicOntology.js +1 -1
- package/lib/publicOntology.js.map +1 -1
- package/lib/serviceConnections.d.ts.map +1 -1
- package/lib/serviceConnections.js +53 -33
- package/lib/serviceConnections.js.map +1 -1
- package/package.json +2 -2
|
@@ -3,10 +3,25 @@ import { Effect } from "effect";
|
|
|
3
3
|
//#region src/core/accessToken.d.ts
|
|
4
4
|
/** Renew an access token this long before it expires. */
|
|
5
5
|
export declare const accessTokenRenewalWindowMs = 60000;
|
|
6
|
+
/** Whether `connectionAccessToken` would refresh this connection before returning a token.
|
|
7
|
+
* An expired refresh token does not invalidate an otherwise usable access token.
|
|
8
|
+
* Renew a minute early so a token is not sent moments before it expires.
|
|
9
|
+
*/
|
|
10
|
+
export declare const accessTokenNeedsRefresh: (connection: {
|
|
11
|
+
readonly status: string;
|
|
12
|
+
readonly accessToken?: unknown;
|
|
13
|
+
readonly accessTokenExpiresAt?: {
|
|
14
|
+
readonly epochMilliseconds: number;
|
|
15
|
+
} | undefined;
|
|
16
|
+
}, now: number) => boolean;
|
|
6
17
|
/** Egress convenience over ordinary reads, refresh action and property decryption.
|
|
18
|
+
* Pass `refresh: false` when the caller coordinates renewal itself, as the connection
|
|
19
|
+
* manager does; the stored token is then returned as is.
|
|
7
20
|
* The supplied backend may be local or remote and must authorize token-property
|
|
8
21
|
* access. This adds no alternate permission path or credential-returning RPC.
|
|
9
22
|
*/
|
|
10
|
-
export declare const connectionAccessToken: (backend: OntologyBackendService, connectionId: string
|
|
23
|
+
export declare const connectionAccessToken: (backend: OntologyBackendService, connectionId: string, options?: {
|
|
24
|
+
readonly refresh?: boolean;
|
|
25
|
+
} | undefined) => Effect.Effect<string, BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, never>;
|
|
11
26
|
//#endregion
|
|
12
27
|
//# sourceMappingURL=accessToken.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"accessToken.d.ts","names":[],"sources":["../../src/core/accessToken.ts"],"mappings":";;;;qBAOa;;;;;
|
|
1
|
+
{"version":3,"file":"accessToken.d.ts","names":[],"sources":["../../src/core/accessToken.ts"],"mappings":";;;;qBAOa;;;;;qBAMA,0BAAuB;WAEnB;WACA;WACA;aAAkC;;GAC9C;;;;;;;qBAmBQ,wBAAqB,SAAA,wBAAA,sBAAA;WAGA;kBAyEhC,OAAA,eAAA"}
|
package/lib/core/accessToken.js
CHANGED
|
@@ -5,6 +5,11 @@ import { TemporalTimestamp } from "@party-stack/ontology-spec/effect";
|
|
|
5
5
|
//#region src/core/accessToken.ts
|
|
6
6
|
/** Renew an access token this long before it expires. */
|
|
7
7
|
const accessTokenRenewalWindowMs = 6e4;
|
|
8
|
+
/** Whether `connectionAccessToken` would refresh this connection before returning a token.
|
|
9
|
+
* An expired refresh token does not invalidate an otherwise usable access token.
|
|
10
|
+
* Renew a minute early so a token is not sent moments before it expires.
|
|
11
|
+
*/
|
|
12
|
+
const accessTokenNeedsRefresh = (connection, now) => !connection.accessToken || connection.status === "inactive" || connection.accessTokenExpiresAt !== void 0 && connection.accessTokenExpiresAt.epochMilliseconds <= now + 6e4;
|
|
8
13
|
const State = Schema.Struct({
|
|
9
14
|
status: Schema.Literals([
|
|
10
15
|
"active",
|
|
@@ -15,10 +20,12 @@ const State = Schema.Struct({
|
|
|
15
20
|
accessTokenExpiresAt: Schema.optional(TemporalTimestamp)
|
|
16
21
|
});
|
|
17
22
|
/** Egress convenience over ordinary reads, refresh action and property decryption.
|
|
23
|
+
* Pass `refresh: false` when the caller coordinates renewal itself, as the connection
|
|
24
|
+
* manager does; the stored token is then returned as is.
|
|
18
25
|
* The supplied backend may be local or remote and must authorize token-property
|
|
19
26
|
* access. This adds no alternate permission path or credential-returning RPC.
|
|
20
27
|
*/
|
|
21
|
-
const connectionAccessToken = Effect.fn("Connect.accessToken")(function* (backend, connectionId) {
|
|
28
|
+
const connectionAccessToken = Effect.fn("Connect.accessToken")(function* (backend, connectionId, options = {}) {
|
|
22
29
|
if (!backend.encrypted) return yield* new BackendError({
|
|
23
30
|
operation: "decrypt",
|
|
24
31
|
kind: "NotImplemented",
|
|
@@ -53,8 +60,7 @@ const connectionAccessToken = Effect.fn("Connect.accessToken")(function* (backen
|
|
|
53
60
|
return row;
|
|
54
61
|
});
|
|
55
62
|
let current = yield* read();
|
|
56
|
-
|
|
57
|
-
if (!current.accessToken || current.status === "inactive" || current.accessTokenExpiresAt && current.accessTokenExpiresAt.epochMilliseconds <= now + 6e4) {
|
|
63
|
+
if (options.refresh !== false && accessTokenNeedsRefresh(current, yield* Clock.currentTimeMillis)) {
|
|
58
64
|
yield* backend.applyAction({
|
|
59
65
|
id: crypto.randomUUID(),
|
|
60
66
|
name: "refreshConnection",
|
|
@@ -84,6 +90,6 @@ const connectionAccessToken = Effect.fn("Connect.accessToken")(function* (backen
|
|
|
84
90
|
})));
|
|
85
91
|
});
|
|
86
92
|
//#endregion
|
|
87
|
-
export { accessTokenRenewalWindowMs, connectionAccessToken };
|
|
93
|
+
export { accessTokenNeedsRefresh, accessTokenRenewalWindowMs, connectionAccessToken };
|
|
88
94
|
|
|
89
95
|
//# sourceMappingURL=accessToken.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"accessToken.js","names":[],"sources":["../../src/core/accessToken.ts"],"sourcesContent":["import { BackendError, EncryptedValueSchema } from \"@party-stack/ontology-backend\";\nimport { TemporalTimestamp } from \"@party-stack/ontology-spec/effect\";\nimport * as q from \"@party-stack/ontology-spec/query\";\nimport { Clock, Effect, Schema } from \"effect\";\nimport type { OntologyBackendService } from \"@party-stack/ontology-backend\";\n\n/** Renew an access token this long before it expires. */\nexport const accessTokenRenewalWindowMs = 60_000;\nconst State = Schema.Struct({\n status: Schema.Literals([\"active\", \"needs-auth\", \"inactive\"]),\n accessToken: Schema.optional(EncryptedValueSchema),\n accessTokenExpiresAt: Schema.optional(TemporalTimestamp),\n});\n\n/** Egress convenience over ordinary reads, refresh action and property decryption.\n * The supplied backend may be local or remote and must authorize token-property\n * access. This adds no alternate permission path or credential-returning RPC.\n */\nexport const connectionAccessToken = Effect.fn(\"Connect.accessToken\")(function* (\n backend: OntologyBackendService,\n connectionId: string\n) {\n if (!backend.encrypted)\n return yield* new BackendError({\n operation: \"decrypt\",\n kind: \"NotImplemented\",\n retryable: false,\n message: \"Connection property decryption is unavailable.\",\n });\n const read = Effect.fnUntraced(function* () {\n const result = yield* backend.query({\n select: [\n q.sub(\"connections\", {\n from: { source: { objectType: \"OAuthConnection\" }, binding: \"connection\" },\n where: q.eq(q.field(\"connection\", \"id\"), q.literal(connectionId)),\n select: [\"status\", \"accessToken\", \"accessTokenExpiresAt\"].map((name) =>\n q.selectField(name, q.field(\"connection\", name))\n ),\n }),\n ],\n });\n const rows = yield* Schema.decodeUnknownEffect(Schema.Array(State))(result.connections).pipe(\n Effect.mapError(\n () =>\n new BackendError({\n operation: \"connect.read\",\n kind: \"InvalidResponse\",\n retryable: false,\n message: \"Connection state is invalid.\",\n })\n )\n );\n const row = rows[0];\n if (!row)\n return yield* new BackendError({\n operation: \"connect.read\",\n kind: \"NotFound\",\n retryable: false,\n message: \"Connection is unavailable.\",\n });\n return row;\n });\n let current = yield* read();\n
|
|
1
|
+
{"version":3,"file":"accessToken.js","names":[],"sources":["../../src/core/accessToken.ts"],"sourcesContent":["import { BackendError, EncryptedValueSchema } from \"@party-stack/ontology-backend\";\nimport { TemporalTimestamp } from \"@party-stack/ontology-spec/effect\";\nimport * as q from \"@party-stack/ontology-spec/query\";\nimport { Clock, Effect, Schema } from \"effect\";\nimport type { OntologyBackendService } from \"@party-stack/ontology-backend\";\n\n/** Renew an access token this long before it expires. */\nexport const accessTokenRenewalWindowMs = 60_000;\n\n/** Whether `connectionAccessToken` would refresh this connection before returning a token.\n * An expired refresh token does not invalidate an otherwise usable access token.\n * Renew a minute early so a token is not sent moments before it expires.\n */\nexport const accessTokenNeedsRefresh = (\n connection: {\n readonly status: string;\n readonly accessToken?: unknown;\n readonly accessTokenExpiresAt?: { readonly epochMilliseconds: number } | undefined;\n },\n now: number\n) =>\n !connection.accessToken ||\n connection.status === \"inactive\" ||\n (connection.accessTokenExpiresAt !== undefined &&\n connection.accessTokenExpiresAt.epochMilliseconds <= now + accessTokenRenewalWindowMs);\nconst State = Schema.Struct({\n status: Schema.Literals([\"active\", \"needs-auth\", \"inactive\"]),\n accessToken: Schema.optional(EncryptedValueSchema),\n accessTokenExpiresAt: Schema.optional(TemporalTimestamp),\n});\n\n/** Egress convenience over ordinary reads, refresh action and property decryption.\n * Pass `refresh: false` when the caller coordinates renewal itself, as the connection\n * manager does; the stored token is then returned as is.\n * The supplied backend may be local or remote and must authorize token-property\n * access. This adds no alternate permission path or credential-returning RPC.\n */\nexport const connectionAccessToken = Effect.fn(\"Connect.accessToken\")(function* (\n backend: OntologyBackendService,\n connectionId: string,\n options: { readonly refresh?: boolean } = {}\n) {\n if (!backend.encrypted)\n return yield* new BackendError({\n operation: \"decrypt\",\n kind: \"NotImplemented\",\n retryable: false,\n message: \"Connection property decryption is unavailable.\",\n });\n const read = Effect.fnUntraced(function* () {\n const result = yield* backend.query({\n select: [\n q.sub(\"connections\", {\n from: { source: { objectType: \"OAuthConnection\" }, binding: \"connection\" },\n where: q.eq(q.field(\"connection\", \"id\"), q.literal(connectionId)),\n select: [\"status\", \"accessToken\", \"accessTokenExpiresAt\"].map((name) =>\n q.selectField(name, q.field(\"connection\", name))\n ),\n }),\n ],\n });\n const rows = yield* Schema.decodeUnknownEffect(Schema.Array(State))(result.connections).pipe(\n Effect.mapError(\n () =>\n new BackendError({\n operation: \"connect.read\",\n kind: \"InvalidResponse\",\n retryable: false,\n message: \"Connection state is invalid.\",\n })\n )\n );\n const row = rows[0];\n if (!row)\n return yield* new BackendError({\n operation: \"connect.read\",\n kind: \"NotFound\",\n retryable: false,\n message: \"Connection is unavailable.\",\n });\n return row;\n });\n let current = yield* read();\n if (options.refresh !== false && accessTokenNeedsRefresh(current, yield* Clock.currentTimeMillis)) {\n yield* backend.applyAction({\n id: crypto.randomUUID(),\n name: \"refreshConnection\",\n parameters: { connectionId },\n });\n current = yield* read();\n }\n if (!current.accessToken)\n return yield* new BackendError({\n operation: \"connect.read\",\n kind: \"Unauthenticated\",\n retryable: false,\n message: \"Access credentials are unavailable.\",\n });\n const result = yield* backend.encrypted.decrypt({\n ...current.accessToken,\n source: { objectType: \"OAuthConnection\", primaryKey: connectionId, property: \"accessToken\" },\n });\n return yield* Schema.decodeUnknownEffect(Schema.String)(result.value).pipe(\n Effect.mapError(\n () =>\n new BackendError({\n operation: \"decrypt\",\n kind: \"InvalidResponse\",\n retryable: false,\n message: \"Connection returned an invalid access token.\",\n })\n )\n );\n});\n"],"mappings":";;;;;;AAOA,MAAa,6BAA6B;;;;;AAM1C,MAAa,2BACT,YAKA,QAEA,CAAC,WAAW,eACZ,WAAW,WAAW,cACrB,WAAW,yBAAyB,KAAA,KACjC,WAAW,qBAAqB,qBAAqB,MA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,YAAY;GACvB,IAAI,OAAO,WAAW;GACtB,MAAM;GACN,YAAY,EAAE,aAAa;EAC/B,CAAC;EACD,UAAU,OAAO,KAAK;CAC1B;CACA,IAAI,CAAC,QAAQ,aACT,OAAO,OAAO,IAAI,aAAa;EAC3B,WAAW;EACX,MAAM;EACN,WAAW;EACX,SAAS;CACb,CAAC;CACL,MAAM,SAAS,OAAO,QAAQ,UAAU,QAAQ;EAC5C,GAAG,QAAQ;EACX,QAAQ;GAAE,YAAY;GAAmB,YAAY;GAAc,UAAU;EAAc;CAC/F,CAAC;CACD,OAAO,OAAO,OAAO,oBAAoB,OAAO,MAAM,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,KAClE,OAAO,eAEC,IAAI,aAAa;EACb,WAAW;EACX,MAAM;EACN,WAAW;EACX,SAAS;CACb,CAAC,CACT,CACJ;AACJ,CAAC"}
|
|
@@ -56,6 +56,11 @@ export interface OAuthAuthorityService {
|
|
|
56
56
|
refresh(connectionId: string): Effect.Effect<OAuthConnectionRecord, ConnectError>;
|
|
57
57
|
disconnect(connectionId: string): Effect.Effect<void, ConnectError>;
|
|
58
58
|
forget(connectionId: string): Effect.Effect<void, ConnectError>;
|
|
59
|
+
/** Expire every credential-operation lease, so the next refresh or reconnect treats it
|
|
60
|
+
* as interrupted. Only a store's sole owner may call this, at startup: any lease it finds
|
|
61
|
+
* was left by a process that stopped mid-operation, not one still running.
|
|
62
|
+
*/
|
|
63
|
+
releaseOperations(): Effect.Effect<number, ConnectError>;
|
|
59
64
|
/** Indexed, bounded maintenance. Does not delete connection identities. */
|
|
60
65
|
collectExpired(options?: {
|
|
61
66
|
limit?: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauthAuthority.d.ts","names":[],"sources":["../../src/core/oauthAuthority.ts"],"mappings":";;;;;;;iBAciB;EACb;EACA,uBAAuB,SAAS;EAChC;EACA,wBAAwB,SAAS;EACjC;EACA;;iBAEa;EACb,iBAAiB;IACb;IACA;IACA;MACA,OAAO,eAAe;EAC1B,SAAS;IACL;IACA;IACA;IACA;MACA,OAAO,OAAO,aAAa;EAC/B,QAAQ,uBAAuB,OAAO,OAAO,aAAa;EAC1D,mBAAmB,OAAO,OAAO,aAAa;EAC9C,QAAQ,gBAAgB,OAAO,aAAa;;iBAE/B;EACb;EACA;EACA;EACA;EACA;;EAEA,aAAa;;iBAEA;EACb,yBACI,wBACD,OAAO,OAAO,mCAAmC;EACpD,MAAM,OAAO,qBAAqB,OAAO;IAAS;IAAY;KAA4B;EAC1F,SAAS;IACL;IACA;MACA,OAAO,OAAO,uBAAuB;EACzC,kBAAkB;IACd;IACA;IACA,aAAa;MACb,OAAO,OAAO,uBAAuB;EACzC,QAAQ,uBAAuB,OAAO,OAAO,uBAAuB;EACpE,WAAW,uBAAuB,OAAO,aAAa;EACtD,OAAO,uBAAuB,OAAO,aAAa;;
|
|
1
|
+
{"version":3,"file":"oauthAuthority.d.ts","names":[],"sources":["../../src/core/oauthAuthority.ts"],"mappings":";;;;;;;iBAciB;EACb;EACA,uBAAuB,SAAS;EAChC;EACA,wBAAwB,SAAS;EACjC;EACA;;iBAEa;EACb,iBAAiB;IACb;IACA;IACA;MACA,OAAO,eAAe;EAC1B,SAAS;IACL;IACA;IACA;IACA;MACA,OAAO,OAAO,aAAa;EAC/B,QAAQ,uBAAuB,OAAO,OAAO,aAAa;EAC1D,mBAAmB,OAAO,OAAO,aAAa;EAC9C,QAAQ,gBAAgB,OAAO,aAAa;;iBAE/B;EACb;EACA;EACA;EACA;EACA;;EAEA,aAAa;;iBAEA;EACb,yBACI,wBACD,OAAO,OAAO,mCAAmC;EACpD,MAAM,OAAO,qBAAqB,OAAO;IAAS;IAAY;KAA4B;EAC1F,SAAS;IACL;IACA;MACA,OAAO,OAAO,uBAAuB;EACzC,kBAAkB;IACd;IACA;IACA,aAAa;MACb,OAAO,OAAO,uBAAuB;EACzC,QAAQ,uBAAuB,OAAO,OAAO,uBAAuB;EACpE,WAAW,uBAAuB,OAAO,aAAa;EACtD,OAAO,uBAAuB,OAAO,aAAa;;;;;EAKlD,qBAAqB,OAAO,eAAe;;EAE3C,eAAe;IACX;MACA,OAAO;IAAS;IAAkB;KAAyB;;iBAElD;EACb,QAAQ,GAAG,IAAI,QAAQ,OAAO,MAAM,GAAG,KAAK,OAAO,IAAI,OAAO,OAAO,UAAU;EAC/E,QAAQ,GAAG,IAAI,QAAQ,OAAO,MAAM,GAAG,KAAK,OAAO,UAAU,KAAK,OAAO,OAAO;EAChF,MAAM,OAAO,qBAAqB,OAAO;;iBAE5B;EACb,OAAO;EACP,QAAQ;EACR,MAAM;IACF,aAAa;IACb,iBAAiB;MACjB,OAAO,OAAO,qBAAqB;;EAEvC,sBACI,SAAS,kCACV,OAAO,OAAO,yBAAyB;;;qBAEjC,uBAAuB;kBAGhB,QAAK,SAAa,0BAAqB,MAAA,MAAA;;;qBA4E9C,qBAAkB,SAAa,0BAAwB,OAAO,OAAO"}
|
|
@@ -115,7 +115,21 @@ const makeOAuthAuthority = (options) => Effect.sync(() => {
|
|
|
115
115
|
const operationId = crypto.randomUUID();
|
|
116
116
|
const record = yield* store.transaction(Effect.gen(function* () {
|
|
117
117
|
const current = yield* read(connectionId);
|
|
118
|
-
|
|
118
|
+
if (current.operationId) {
|
|
119
|
+
if (!expired(current.operationExpiresAt, yield* Clock.currentTimeMillis)) return yield* connectError("Busy", "Connection operation is in progress.", true);
|
|
120
|
+
if ((yield* store.get("OAuthApplication", current.application))?.flow !== "client-credentials") {
|
|
121
|
+
yield* evict(current.refreshToken);
|
|
122
|
+
yield* store.put("OAuthConnection", {
|
|
123
|
+
...current,
|
|
124
|
+
status: "needs-auth",
|
|
125
|
+
refreshToken: void 0,
|
|
126
|
+
refreshTokenExpiresAt: void 0,
|
|
127
|
+
operationId: void 0,
|
|
128
|
+
operationExpiresAt: void 0
|
|
129
|
+
});
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
119
133
|
if (current.status !== "active") return yield* connectError("NeedsAuthentication", "Reconnect this connection.");
|
|
120
134
|
const next = {
|
|
121
135
|
...current,
|
|
@@ -125,6 +139,7 @@ const makeOAuthAuthority = (options) => Effect.sync(() => {
|
|
|
125
139
|
yield* store.put("OAuthConnection", next);
|
|
126
140
|
return next;
|
|
127
141
|
}));
|
|
142
|
+
if (!record) return yield* connectError("NeedsAuthentication", "An interrupted credential operation requires reconnection.");
|
|
128
143
|
return yield* Effect.gen(function* () {
|
|
129
144
|
const { application, oauth } = yield* configured(record.application);
|
|
130
145
|
let tokens;
|
|
@@ -294,14 +309,16 @@ const makeOAuthAuthority = (options) => Effect.sync(() => {
|
|
|
294
309
|
yield* store.transaction(Effect.gen(function* () {
|
|
295
310
|
const existing = yield* store.get("OAuthConnection", connectionId);
|
|
296
311
|
if (existing && existing.application !== application.id) return yield* connectError("Forbidden", "Connection belongs to another application.");
|
|
297
|
-
if (existing) yield* busy(existing);
|
|
312
|
+
if (existing) yield* busy(existing, true);
|
|
298
313
|
yield* store.put("OAuthConnection", {
|
|
299
314
|
...input.properties,
|
|
300
315
|
...existing,
|
|
301
316
|
id: connectionId,
|
|
302
317
|
title: existing?.title ?? application.title,
|
|
303
318
|
application: application.id,
|
|
304
|
-
status: "active"
|
|
319
|
+
status: "active",
|
|
320
|
+
operationId: void 0,
|
|
321
|
+
operationExpiresAt: void 0
|
|
305
322
|
});
|
|
306
323
|
const latest = yield* store.get("OAuthApplication", application.id);
|
|
307
324
|
if (!latest) return yield* connectError("NotFound", "OAuth application is unavailable.");
|
|
@@ -370,6 +387,16 @@ const makeOAuthAuthority = (options) => Effect.sync(() => {
|
|
|
370
387
|
if (oauth.revoke) yield* oauth.revoke(Redacted.value(removed.plaintext));
|
|
371
388
|
}
|
|
372
389
|
}),
|
|
390
|
+
releaseOperations: Effect.fn("Connect.releaseOperations")(function* () {
|
|
391
|
+
return yield* store.transaction(Effect.gen(function* () {
|
|
392
|
+
const held = yield* store.load("OAuthConnection", { where: ne(field("operationId"), void 0) });
|
|
393
|
+
for (const record of held) yield* store.put("OAuthConnection", {
|
|
394
|
+
...record,
|
|
395
|
+
operationExpiresAt: instant(0)
|
|
396
|
+
});
|
|
397
|
+
return held.length;
|
|
398
|
+
}));
|
|
399
|
+
}),
|
|
373
400
|
collectExpired: Effect.fn("Connect.collectExpired")(function* ({ limit = 100 } = {}) {
|
|
374
401
|
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e3) return yield* connectError("Configuration", "GC batch size must be between 1 and 1000.");
|
|
375
402
|
return yield* store.transaction(Effect.gen(function* () {
|
|
@@ -1 +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// Schemes that can execute, embed or read local content are never redirect targets.\nconst unsafeRedirectSchemes = new Set([\n \"about:\",\n \"blob:\",\n \"data:\",\n \"file:\",\n \"filesystem:\",\n \"ftp:\",\n \"javascript:\",\n \"vbscript:\",\n \"ws:\",\n \"wss:\",\n]);\nconst nativeRedirect = (url: URL) =>\n /^[a-z][a-z0-9+.-]*:$/.test(url.protocol) &&\n url.protocol !== \"http:\" &&\n url.protocol !== \"https:\" &&\n !unsafeRedirectSchemes.has(url.protocol) &&\n !url.username &&\n !url.password &&\n !url.port &&\n !url.hash;\n/** Network redirects keep the HTTPS policy. A native application may instead\n * receive its callback at a custom scheme, but only at the exact redirect its\n * trusted OAuth application registration declares; callers cannot introduce one.\n */\nconst guardRedirectUrl = (value: string, registered: string | undefined) =>\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 return url;\n if (registered !== undefined && value === registered && nativeRedirect(url)) return url;\n throw new Error();\n },\n catch: () =>\n connectError(\n \"Configuration\",\n \"OAuth redirect URLs require HTTPS, HTTP on localhost, or the application's registered native redirect.\"\n ),\n });\n/** Callback URLs are parsed before the attempt is known; its accepted redirect\n * then decides the exact scheme, host and path. URL.origin is \"null\" for custom\n * schemes, so compare those parts explicitly.\n */\nconst sameRedirectTarget = (expected: URL, callback: URL) =>\n expected.protocol === callback.protocol &&\n expected.host === callback.host &&\n expected.pathname === callback.pathname &&\n expected.username === callback.username &&\n expected.password === callback.password;\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 if (input.returnUrl) yield* guardUrl(input.returnUrl);\n const { application, oauth } = yield* configured(input.applicationId);\n yield* guardRedirectUrl(input.redirectUrl, application.redirectUrl);\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* Effect.try({\n try: () => new URL(input.callbackUrl),\n catch: () => connectError(\"InvalidAttempt\", \"Authorization callback URL is invalid.\"),\n });\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 (!sameRedirectTarget(expected, callback))\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,WA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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 /** Expire every credential-operation lease, so the next refresh or reconnect treats it\n * as interrupted. Only a store's sole owner may call this, at startup: any lease it finds\n * was left by a process that stopped mid-operation, not one still running.\n */\n releaseOperations(): Effect.Effect<number, 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// Schemes that can execute, embed or read local content are never redirect targets.\nconst unsafeRedirectSchemes = new Set([\n \"about:\",\n \"blob:\",\n \"data:\",\n \"file:\",\n \"filesystem:\",\n \"ftp:\",\n \"javascript:\",\n \"vbscript:\",\n \"ws:\",\n \"wss:\",\n]);\nconst nativeRedirect = (url: URL) =>\n /^[a-z][a-z0-9+.-]*:$/.test(url.protocol) &&\n url.protocol !== \"http:\" &&\n url.protocol !== \"https:\" &&\n !unsafeRedirectSchemes.has(url.protocol) &&\n !url.username &&\n !url.password &&\n !url.port &&\n !url.hash;\n/** Network redirects keep the HTTPS policy. A native application may instead\n * receive its callback at a custom scheme, but only at the exact redirect its\n * trusted OAuth application registration declares; callers cannot introduce one.\n */\nconst guardRedirectUrl = (value: string, registered: string | undefined) =>\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 return url;\n if (registered !== undefined && value === registered && nativeRedirect(url)) return url;\n throw new Error();\n },\n catch: () =>\n connectError(\n \"Configuration\",\n \"OAuth redirect URLs require HTTPS, HTTP on localhost, or the application's registered native redirect.\"\n ),\n });\n/** Callback URLs are parsed before the attempt is known; its accepted redirect\n * then decides the exact scheme, host and path. URL.origin is \"null\" for custom\n * schemes, so compare those parts explicitly.\n */\nconst sameRedirectTarget = (expected: URL, callback: URL) =>\n expected.protocol === callback.protocol &&\n expected.host === callback.host &&\n expected.pathname === callback.pathname &&\n expected.username === callback.username &&\n expected.password === callback.password;\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 if (current.operationId) {\n if (!expired(current.operationExpiresAt, yield* Clock.currentTimeMillis))\n return yield* connectError(\"Busy\", \"Connection operation is in progress.\", true);\n // An interrupted refresh may have rotated the refresh token before its\n // reply was lost, so never retry it blindly; save that the connection\n // needs a sign-in. Client credentials hold no such token: claim and fetch anew.\n const application = yield* store.get(\"OAuthApplication\", current.application);\n if (application?.flow !== \"client-credentials\") {\n yield* evict(current.refreshToken);\n yield* store.put(\"OAuthConnection\", {\n ...current,\n status: \"needs-auth\",\n refreshToken: undefined,\n refreshTokenExpiresAt: undefined,\n operationId: undefined,\n operationExpiresAt: undefined,\n });\n return undefined;\n }\n }\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 if (!record)\n return yield* connectError(\n \"NeedsAuthentication\",\n \"An interrupted credential operation requires reconnection.\"\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 if (input.returnUrl) yield* guardUrl(input.returnUrl);\n const { application, oauth } = yield* configured(input.applicationId);\n yield* guardRedirectUrl(input.redirectUrl, application.redirectUrl);\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* Effect.try({\n try: () => new URL(input.callbackUrl),\n catch: () => connectError(\"InvalidAttempt\", \"Authorization callback URL is invalid.\"),\n });\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 (!sameRedirectTarget(expected, callback))\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 // Reconnecting is how a client-credentials connection recovers from an\n // interrupted operation, so an expired lease does not block it.\n if (existing) yield* busy(existing, true);\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 operationId: undefined,\n operationExpiresAt: undefined,\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 releaseOperations: Effect.fn(\"Connect.releaseOperations\")(function* () {\n return yield* store.transaction(\n Effect.gen(function* () {\n const held = yield* store.load(\"OAuthConnection\", {\n where: ne(field(\"operationId\"), undefined),\n });\n for (const record of held)\n yield* store.put(\"OAuthConnection\", {\n ...record,\n operationExpiresAt: instant(0),\n });\n return held.length;\n })\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":";;;;;;AA2FA,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,MAAM,wCAAwB,IAAI,IAAI;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACJ,CAAC;AACD,MAAM,kBAAkB,QACpB,uBAAuB,KAAK,IAAI,QAAQ,KACxC,IAAI,aAAa,WACjB,IAAI,aAAa,YACjB,CAAC,sBAAsB,IAAI,IAAI,QAAQ,KACvC,CAAC,IAAI,YACL,CAAC,IAAI,YACL,CAAC,IAAI,QACL,CAAC,IAAI;;;;;AAKT,MAAM,oBAAoB,OAAe,eACrC,OAAO,IAAI;CACP,WAAW;EACP,MAAM,MAAM,IA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AAC;CACL,CAAC;AACL,CAAC"}
|
package/lib/index.d.ts
CHANGED
|
@@ -8,7 +8,6 @@ import { withHttpAuthenticationErrors } from "./withHttpAuthenticationErrors.js"
|
|
|
8
8
|
import { OAuthServiceOptions, makeOAuthService } from "./core/oauth.js";
|
|
9
9
|
import { makeServerConnectClient } from "./serverClient.js";
|
|
10
10
|
import { ConnectActionHandler, makeConnectBackend } from "./core/backend.js";
|
|
11
|
-
import { connectionAccessToken } from "./core/accessToken.js";
|
|
12
11
|
import { OAuthAuthorizationClient, OAuthAuthorizationSource, bindOAuthAuthorizationBackend, makeOAuthAuthorizationClient, oauthAuthorizationOntology } from "./authorization.js";
|
|
13
12
|
import { runtimeCredentialValues } from "./oauth/storage.js";
|
|
14
13
|
import { connectDeviceRoute, connectPublicOntologyIR } from "./publicOntology.js";
|
|
@@ -17,4 +16,4 @@ import { ConnectionAccess } from "./serviceConnections.js";
|
|
|
17
16
|
import { toWebEgress } from "./toWebEgress.js";
|
|
18
17
|
import { ConnectInstanceConfiguration, ConnectManager, ConnectManagerOptions, ConnectManagerService, ConnectOAuthApplicationConfiguration, ConnectServiceConfiguration, makeConnectManager } from "./makeConnectManager.js";
|
|
19
18
|
import { acquireConfiguredConnection } from "./acquireConfiguredConnection.js";
|
|
20
|
-
export { type AccountRef, type AccountSummary, type AuthenticationClient, type BeginAuthorization, type ConnectActionHandler, type ConnectCredentialValues, ConnectError, type ConnectInstanceConfiguration, ConnectManager, type ConnectManagerOptions, type ConnectManagerService, type ConnectOAuthApplicationConfiguration, type ConnectOAuthService, type ConnectServiceConfiguration, type ConnectStore, type Connection, type ConnectionAccess, type ConnectionEgress, type ConnectionEgressHandlers, type ConnectionLifecycle, type ConnectionMonitor, type ConnectionRef, type ConnectionState, ConnectionStateSchema, type ConnectionStatus, type OAuthAuthorizationClient, type OAuthAuthorizationSource, type OAuthServiceOptions, type OAuthTokens, type SavedConnection, type ServiceConnector, type VerifiedServiceIdentity, acquireConfiguredConnection, bindOAuthAuthorizationBackend, connectDeviceRoute, connectPublicOntologyIR,
|
|
19
|
+
export { type AccountRef, type AccountSummary, type AuthenticationClient, type BeginAuthorization, type ConnectActionHandler, type ConnectCredentialValues, ConnectError, type ConnectInstanceConfiguration, ConnectManager, type ConnectManagerOptions, type ConnectManagerService, type ConnectOAuthApplicationConfiguration, type ConnectOAuthService, type ConnectServiceConfiguration, type ConnectStore, type Connection, type ConnectionAccess, type ConnectionEgress, type ConnectionEgressHandlers, type ConnectionLifecycle, type ConnectionMonitor, type ConnectionRef, type ConnectionState, ConnectionStateSchema, type ConnectionStatus, type OAuthAuthorizationClient, type OAuthAuthorizationSource, type OAuthServiceOptions, type OAuthTokens, type SavedConnection, type ServiceConnector, type VerifiedServiceIdentity, acquireConfiguredConnection, bindOAuthAuthorizationBackend, connectDeviceRoute, connectPublicOntologyIR, createDefaultConnectionEgressHandlers, makeAuthenticationClient, makeConnectBackend, makeConnectManager, makeConnectStore, makeOAuthAuthorizationClient, makeOAuthService, makeServerConnectClient, oauthAuthorizationOntology, runtimeCredentialValues, toWebEgress, withHttpAuthenticationErrors };
|
package/lib/index.js
CHANGED
|
@@ -8,10 +8,9 @@ import { createDefaultConnectionEgressHandlers } from "./createDefaultConnection
|
|
|
8
8
|
import { ConnectionStateSchema } from "./types.js";
|
|
9
9
|
import { withHttpAuthenticationErrors } from "./withHttpAuthenticationErrors.js";
|
|
10
10
|
import { runtimeCredentialValues } from "./oauth/storage.js";
|
|
11
|
-
import { connectionAccessToken } from "./core/accessToken.js";
|
|
12
11
|
import { ConnectManager, makeConnectManager } from "./makeConnectManager.js";
|
|
13
12
|
import { makeOAuthService } from "./core/oauth.js";
|
|
14
13
|
import { makeServerConnectClient } from "./serverClient.js";
|
|
15
14
|
import { connectDeviceRoute, connectPublicOntologyIR } from "./publicOntology.js";
|
|
16
15
|
import { toWebEgress } from "./toWebEgress.js";
|
|
17
|
-
export { ConnectError, ConnectManager, ConnectionStateSchema, acquireConfiguredConnection, bindOAuthAuthorizationBackend, connectDeviceRoute, connectPublicOntologyIR,
|
|
16
|
+
export { ConnectError, ConnectManager, ConnectionStateSchema, acquireConfiguredConnection, bindOAuthAuthorizationBackend, connectDeviceRoute, connectPublicOntologyIR, createDefaultConnectionEgressHandlers, makeAuthenticationClient, makeConnectBackend, makeConnectManager, makeConnectStore, makeOAuthAuthorizationClient, makeOAuthService, makeServerConnectClient, oauthAuthorizationOntology, runtimeCredentialValues, toWebEgress, withHttpAuthenticationErrors };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"makeConnectManager.d.ts","names":["_$__core_oauthAuthority_js0.OAuthAuthorityService","_$__index_js0.ConnectStore","_$__index_js0.ConnectCredentialValues","_$__ServiceConnector_js0.ConnectionRef","_$__types_js0.ConnectionEgress","_$__types_js0.ConnectionLifecycle"],"sources":["../src/makeConnectManager.ts"],"mappings":";;;;;;;;;;;;;;;;iBAeiB,6CAA6C,KAC1D;WAGS;WACA;WACA,OAAO;;iBAEH,qCAAqC,KAClD;WAGS;WACA;WACA,6BAA6B;;iBAEzB;WACJ,WAAW;WACX,qBAAqB;;iBAEjB;WACJ,KAAK;WACL,iBAAiB,SAAS,eAAe;WACzC;WACA,mBAAmB;;WAEnB;WACA;aAAyB;;;qBAEzB,qBAAkB,SAAA,0BAAA,OAAA;;WAAAA;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"makeConnectManager.d.ts","names":["_$__core_oauthAuthority_js0.OAuthAuthorityService","_$__index_js0.ConnectStore","_$__index_js0.ConnectCredentialValues","_$__ServiceConnector_js0.ConnectionRef","_$__types_js0.ConnectionEgress","_$__types_js0.ConnectionLifecycle"],"sources":["../src/makeConnectManager.ts"],"mappings":";;;;;;;;;;;;;;;;iBAeiB,6CAA6C,KAC1D;WAGS;WACA;WACA,OAAO;;iBAEH,qCAAqC,KAClD;WAGS;WACA;WACA,6BAA6B;;iBAEzB;WACJ,WAAW;WACX,qBAAqB;;iBAEjB;WACJ,KAAK;WACL,iBAAiB,SAAS,eAAe;WACzC;WACA,mBAAmB;;WAEnB;WACA;aAAyB;;;qBAEzB,qBAAkB,SAAA,0BAAA,OAAA;;WAAAA;;;;;;;;;;;;;;;;IA8EgC,KAAG,OAAA,aAAA;;GAChE,iWAAA,iCAAA;YAEU,wBAAwB,OAAO,QAAQ,kBAAkB;;;;;;;;;;;;;;;;;;;IAHN,KAAG,OAAA,aAAA;;;qBAIrD,uBAAuB;kBAGhB,QAAK,SAAa,0BAAqB,MAAA,MAAA,gBAAA,iWAAA"}
|
|
@@ -69,6 +69,7 @@ const makeConnectManager = Effect.fn("ConnectManager.make")(function* (options)
|
|
|
69
69
|
});
|
|
70
70
|
}
|
|
71
71
|
})).pipe(Effect.mapError(connectBackendError));
|
|
72
|
+
yield* authority.connect.releaseOperations().pipe(Effect.mapError(connectBackendError));
|
|
72
73
|
yield* authority.connect.collectExpired().pipe(Effect.mapError(connectBackendError));
|
|
73
74
|
const connections = yield* makeServiceConnections({
|
|
74
75
|
backend: authority.backend,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"makeConnectManager.js","names":[],"sources":["../src/makeConnectManager.ts"],"sourcesContent":["import { BackendError } from \"@party-stack/ontology-backend\";\nimport { Runtime } from \"@party-stack/runtime\";\nimport { Context, Effect, Layer } from \"effect\";\nimport { makeConnectBackend, connectBackendError } from \"./core/backend.js\";\nimport { runtimeCredentialValues } from \"./oauth/storage.js\";\nimport { makeServiceConnections } from \"./serviceConnections.js\";\nimport type { ConnectActionHandler } from \"./core/backend.js\";\nimport type { ServiceConnector } from \"./ServiceConnector.js\";\nimport type { OAuthApplicationRecord, ServiceInstanceRecord } from \"./spec/index.js\";\nimport type { OntologyIR } from \"@party-stack/ontology-spec\";\n\n/** A device/server credential owner. Runtime supplies Tables and key storage;\n * service integrations supply authentication/egress, and the ontology stores inventory.\n * Expose backend through a policy-bound ordinary ontology server.\n */\nexport interface ConnectOAuthApplicationConfiguration extends Omit<\n OAuthApplicationRecord,\n \"serviceInstance\" | \"id\" | \"title\" | \"flow\"\n> {\n readonly id?: string;\n readonly title?: string;\n readonly flow?: OAuthApplicationRecord[\"flow\"];\n}\nexport interface ConnectInstanceConfiguration extends Omit<\n ServiceInstanceRecord,\n \"service\" | \"id\" | \"title\"\n> {\n readonly id?: string;\n readonly title?: string;\n readonly OAuthApplications?: readonly ConnectOAuthApplicationConfiguration[];\n}\nexport interface ConnectServiceConfiguration {\n readonly connector: ServiceConnector;\n readonly instances?: readonly ConnectInstanceConfiguration[];\n}\nexport interface ConnectManagerOptions {\n readonly ir?: OntologyIR;\n readonly actionHandlers?: Readonly<Record<string, ConnectActionHandler>>;\n readonly namespace?: string;\n readonly services: readonly ConnectServiceConfiguration[];\n /** Start the scoped periodic sweep. Alarms/jobs call maintenance.run themselves. */\n readonly startMaintenance?: boolean;\n readonly maintenance?: { readonly intervalMs?: number };\n}\nexport const makeConnectManager = Effect.fn(\"ConnectManager.make\")(function* (\n options: ConnectManagerOptions\n) {\n const runtime = yield* Runtime;\n const namespace = options.namespace ?? runtime.namespace;\n const values = yield* runtimeCredentialValues(runtime, namespace).pipe(\n Effect.mapError(connectBackendError)\n );\n const instances: ServiceInstanceRecord[] = [];\n const applications: OAuthApplicationRecord[] = [];\n for (const configured of options.services) {\n const { connector } = configured;\n for (const { OAuthApplications, ...instance } of configured.instances ?? []) {\n const canonicalUrl = yield* Effect.try({\n try: () => new URL(instance.instanceUrl).href.replace(/\\/+$/, \"\"),\n catch: () =>\n new BackendError({\n operation: \"connect.configure\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"A service instance must have an absolute URL.\",\n }),\n });\n const id = instance.id ?? JSON.stringify([connector.service, canonicalUrl]);\n const title = instance.title ?? connector.displayName ?? connector.service;\n instances.push({ ...instance, id, title, service: connector.service });\n for (const application of OAuthApplications ?? []) {\n const scopes = application.scopes ?? connector.defaultOAuthScopes;\n applications.push({\n ...application,\n id: application.id ?? JSON.stringify([id, application.clientId]),\n title: application.title ?? title,\n flow: application.flow ?? \"authorization-code\",\n scopes: scopes === undefined ? undefined : [...scopes],\n serviceInstance: id,\n });\n }\n }\n }\n if (\n new Set(instances.map((row) => row.id)).size !== instances.length ||\n new Set(applications.map((row) => row.id)).size !== applications.length\n )\n return yield* new BackendError({\n operation: \"connect.configure\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"Service instance and OAuth application IDs must be unique.\",\n });\n const authority = yield* makeConnectBackend({\n ir: options.ir,\n actionHandlers: options.actionHandlers,\n tables: runtime.tables,\n namespace,\n values,\n services: options.services.map((entry) => entry.connector),\n maintenance: options.startMaintenance === false ? false : options.maintenance,\n });\n yield* authority.store\n .transaction(\n Effect.gen(function* () {\n for (const instance of instances) yield* authority.store.put(\"ServiceInstance\", instance);\n for (const application of applications) {\n const previous = yield* authority.store.get(\"OAuthApplication\", application.id);\n yield* authority.store.put(\"OAuthApplication\", { ...previous, ...application });\n }\n })\n )\n .pipe(Effect.mapError(connectBackendError));\n yield* authority.connect.collectExpired().pipe(Effect.mapError(connectBackendError));\n const connections = yield* makeServiceConnections({\n backend: authority.backend,\n store: authority.store,\n services: options.services.map((entry) => entry.connector),\n });\n return { ...authority, values, connections, maintenance: { run: authority.backend.maintenance! } };\n});\n\nexport type ConnectManagerService = Effect.Success<ReturnType<typeof makeConnectManager>>;\nexport class ConnectManager extends Context.Service<ConnectManager, ConnectManagerService>()(\n \"@party-stack/connect/ConnectManager\"\n) {\n static readonly layer = (options: ConnectManagerOptions) =>\n Layer.effect(ConnectManager, makeConnectManager(options));\n}\n"],"mappings":";;;;;;;AA4CA,MAAa,qBAAqB,OAAO,GAAG,qBAAqB,CAAC,CAAC,WAC/D,SACF;CACE,MAAM,UAAU,OAAO;CACvB,MAAM,YAAY,QAAQ,aAAa,QAAQ;CAC/C,MAAM,SAAS,OAAO,wBAAwB,SAAS,SAAS,CAAC,CAAC,KAC9D,OAAO,SAAS,mBAAmB,CACvC;CACA,MAAM,YAAqC,CAAC;CAC5C,MAAM,eAAyC,C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AQ,SAAS,KAAK,UAAU,MAAM,SAAS;EACzD,aAAa,QAAQ,qBAAqB,QAAQ,QAAQ,QAAQ;CACtE,CAAC;CACD,OAAO,UAAU,MACZ,YACG,OAAO,IAAI,aAAa;EACpB,KAAK,MAAM,YAAY,WAAW,OAAO,UAAU,MAAM,IAAI,mBAAmB,QAAQ;EACxF,KAAK,MAAM,eAAe,cAAc;GACpC,MAAM,WAAW,OAAO,UAAU,MAAM,IAAI,oBAAoB,YAAY,EAAE;GAC9E,OAAO,UAAU,MAAM,IAAI,oBAAoB;IAAE,GAAG;IAAU,GAAG;GAAY,CAAC;EAClF;CACJ,CAAC,CACL,CAAC,CACA,KAAK,OAAO,SAAS,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"makeConnectManager.js","names":[],"sources":["../src/makeConnectManager.ts"],"sourcesContent":["import { BackendError } from \"@party-stack/ontology-backend\";\nimport { Runtime } from \"@party-stack/runtime\";\nimport { Context, Effect, Layer } from \"effect\";\nimport { makeConnectBackend, connectBackendError } from \"./core/backend.js\";\nimport { runtimeCredentialValues } from \"./oauth/storage.js\";\nimport { makeServiceConnections } from \"./serviceConnections.js\";\nimport type { ConnectActionHandler } from \"./core/backend.js\";\nimport type { ServiceConnector } from \"./ServiceConnector.js\";\nimport type { OAuthApplicationRecord, ServiceInstanceRecord } from \"./spec/index.js\";\nimport type { OntologyIR } from \"@party-stack/ontology-spec\";\n\n/** A device/server credential owner. Runtime supplies Tables and key storage;\n * service integrations supply authentication/egress, and the ontology stores inventory.\n * Expose backend through a policy-bound ordinary ontology server.\n */\nexport interface ConnectOAuthApplicationConfiguration extends Omit<\n OAuthApplicationRecord,\n \"serviceInstance\" | \"id\" | \"title\" | \"flow\"\n> {\n readonly id?: string;\n readonly title?: string;\n readonly flow?: OAuthApplicationRecord[\"flow\"];\n}\nexport interface ConnectInstanceConfiguration extends Omit<\n ServiceInstanceRecord,\n \"service\" | \"id\" | \"title\"\n> {\n readonly id?: string;\n readonly title?: string;\n readonly OAuthApplications?: readonly ConnectOAuthApplicationConfiguration[];\n}\nexport interface ConnectServiceConfiguration {\n readonly connector: ServiceConnector;\n readonly instances?: readonly ConnectInstanceConfiguration[];\n}\nexport interface ConnectManagerOptions {\n readonly ir?: OntologyIR;\n readonly actionHandlers?: Readonly<Record<string, ConnectActionHandler>>;\n readonly namespace?: string;\n readonly services: readonly ConnectServiceConfiguration[];\n /** Start the scoped periodic sweep. Alarms/jobs call maintenance.run themselves. */\n readonly startMaintenance?: boolean;\n readonly maintenance?: { readonly intervalMs?: number };\n}\nexport const makeConnectManager = Effect.fn(\"ConnectManager.make\")(function* (\n options: ConnectManagerOptions\n) {\n const runtime = yield* Runtime;\n const namespace = options.namespace ?? runtime.namespace;\n const values = yield* runtimeCredentialValues(runtime, namespace).pipe(\n Effect.mapError(connectBackendError)\n );\n const instances: ServiceInstanceRecord[] = [];\n const applications: OAuthApplicationRecord[] = [];\n for (const configured of options.services) {\n const { connector } = configured;\n for (const { OAuthApplications, ...instance } of configured.instances ?? []) {\n const canonicalUrl = yield* Effect.try({\n try: () => new URL(instance.instanceUrl).href.replace(/\\/+$/, \"\"),\n catch: () =>\n new BackendError({\n operation: \"connect.configure\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"A service instance must have an absolute URL.\",\n }),\n });\n const id = instance.id ?? JSON.stringify([connector.service, canonicalUrl]);\n const title = instance.title ?? connector.displayName ?? connector.service;\n instances.push({ ...instance, id, title, service: connector.service });\n for (const application of OAuthApplications ?? []) {\n const scopes = application.scopes ?? connector.defaultOAuthScopes;\n applications.push({\n ...application,\n id: application.id ?? JSON.stringify([id, application.clientId]),\n title: application.title ?? title,\n flow: application.flow ?? \"authorization-code\",\n scopes: scopes === undefined ? undefined : [...scopes],\n serviceInstance: id,\n });\n }\n }\n }\n if (\n new Set(instances.map((row) => row.id)).size !== instances.length ||\n new Set(applications.map((row) => row.id)).size !== applications.length\n )\n return yield* new BackendError({\n operation: \"connect.configure\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"Service instance and OAuth application IDs must be unique.\",\n });\n const authority = yield* makeConnectBackend({\n ir: options.ir,\n actionHandlers: options.actionHandlers,\n tables: runtime.tables,\n namespace,\n values,\n services: options.services.map((entry) => entry.connector),\n maintenance: options.startMaintenance === false ? false : options.maintenance,\n });\n yield* authority.store\n .transaction(\n Effect.gen(function* () {\n for (const instance of instances) yield* authority.store.put(\"ServiceInstance\", instance);\n for (const application of applications) {\n const previous = yield* authority.store.get(\"OAuthApplication\", application.id);\n yield* authority.store.put(\"OAuthApplication\", { ...previous, ...application });\n }\n })\n )\n .pipe(Effect.mapError(connectBackendError));\n // The manager owns this store, so a lease it finds at startup belongs to a process that\n // stopped mid-refresh. Release it now rather than failing refreshes until it expires.\n yield* authority.connect.releaseOperations().pipe(Effect.mapError(connectBackendError));\n yield* authority.connect.collectExpired().pipe(Effect.mapError(connectBackendError));\n const connections = yield* makeServiceConnections({\n backend: authority.backend,\n store: authority.store,\n services: options.services.map((entry) => entry.connector),\n });\n return { ...authority, values, connections, maintenance: { run: authority.backend.maintenance! } };\n});\n\nexport type ConnectManagerService = Effect.Success<ReturnType<typeof makeConnectManager>>;\nexport class ConnectManager extends Context.Service<ConnectManager, ConnectManagerService>()(\n \"@party-stack/connect/ConnectManager\"\n) {\n static readonly layer = (options: ConnectManagerOptions) =>\n Layer.effect(ConnectManager, makeConnectManager(options));\n}\n"],"mappings":";;;;;;;AA4CA,MAAa,qBAAqB,OAAO,GAAG,qBAAqB,CAAC,CAAC,WAC/D,SACF;CACE,MAAM,UAAU,OAAO;CACvB,MAAM,YAAY,QAAQ,aAAa,QAAQ;CAC/C,MAAM,SAAS,OAAO,wBAAwB,SAAS,SAAS,CAAC,CAAC,KAC9D,OAAO,SAAS,mBAAmB,CACvC;CACA,MAAM,YAAqC,CAAC;CAC5C,MAAM,eAAyC,CAAC;CAChD,KAAK,MAAM,cAAc,QAAQ,UAAU;EACvC,MAAM,EAAE,cAAc;EACtB,KAAK,MAA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;CACtE,CAAC;CACD,OAAO,UAAU,MACZ,YACG,OAAO,IAAI,aAAa;EACpB,KAAK,MAAM,YAAY,WAAW,OAAO,UAAU,MAAM,IAAI,mBAAmB,QAAQ;EACxF,KAAK,MAAM,eAAe,cAAc;GACpC,MAAM,WAAW,OAAO,UAAU,MAAM,IAAI,oBAAoB,YAAY,EAAE;GAC9E,OAAO,UAAU,MAAM,IAAI,oBAAoB;IAAE,GAAG;IAAU,GAAG;GAAY,CAAC;EAClF;CACJ,CAAC,CACL,CAAC,CACA,KAAK,OAAO,SAAS,mBAAmB,CAAC;CAG9C,OAAO,UAAU,QAAQ,kBAAkB,CAAC,CAAC,KAAK,OAAO,SAAS,mBAAmB,CAAC;CACtF,OAAO,UAAU,QAAQ,eAAe,CAAC,CAAC,KAAK,OAAO,SAAS,mBAAmB,CAAC;CACnF,MAAM,cAAc,OAAO,uBAAuB;EAC9C,SAAS,UAAU;EACnB,OAAO,UAAU;EACjB,UAAU,QAAQ,SAAS,KAAK,UAAU,MAAM,SAAS;CAC7D,CAAC;CACD,OAAO;EAAE,GAAG;EAAW;EAAQ;EAAa,aAAa,EAAE,KAAK,UAAU,QAAQ,YAAa;CAAE;AACrG,CAAC;AAGD,IAAa,iBAAb,MAAa,uBAAuB,QAAQ,QAA+C,CAAC,CACxF,qCACJ,CAAC,CAAC;CACE,OAAgB,SAAS,YACrB,MAAM,OAAO,gBAAgB,mBAAmB,OAAO,CAAC;AAChE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"publicOntology.d.ts","names":[],"sources":["../src/publicOntology.ts"],"mappings":";;;qBAuCa,yBAAyB;;;;;;
|
|
1
|
+
{"version":3,"file":"publicOntology.d.ts","names":[],"sources":["../src/publicOntology.ts"],"mappings":";;;qBAuCa,yBAAyB;;;;;;wBA6BtB,mBAAmB,SAAS,KAAK;EAEzC;EACA,iDAAO;EACP,IAAE;EACF"}
|
package/lib/publicOntology.js
CHANGED
|
@@ -57,7 +57,7 @@ const connectPublicOntologyIR = {
|
|
|
57
57
|
objects: read,
|
|
58
58
|
actions: connectOntology.actionTypes.map((action) => ({
|
|
59
59
|
actionType: action.name,
|
|
60
|
-
check: action.name === "beginAuthorization" ? q.exists({
|
|
60
|
+
check: action.name === "refreshConnection" ? q.literal(false) : action.name === "beginAuthorization" ? q.exists({
|
|
61
61
|
from: {
|
|
62
62
|
source: { objectType: "OAuthApplication" },
|
|
63
63
|
binding: "app"
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"publicOntology.js","names":[],"sources":["../src/publicOntology.ts"],"sourcesContent":["import * as q from \"@party-stack/ontology-spec/query\";\nimport { connectOntology } from \"./spec/index.js\";\nimport type { ConnectManagerService } from \"./makeConnectManager.js\";\nimport type { OntologyIR } from \"@party-stack/ontology-spec\";\n\n/** Device-local public view. It exposes inventory and authentication actions while\n * retaining token ciphertext and PKCE records at the credential owner. Public servers\n * must additionally scope instances/connections to their authenticated caller.\n */\nconst read = {\n select: [\n q.sub(\"services\", {\n from: { source: { objectType: \"ServiceInstance\" }, binding: \"s\" },\n select: [\"id\", \"title\", \"service\", \"instanceUrl\"].map((name) =>\n q.selectField(name, q.field(\"s\", name))\n ),\n }),\n q.sub(\"applications\", {\n from: { source: { objectType: \"OAuthApplication\" }, binding: \"app\" },\n select: [\"id\", \"title\", \"serviceInstance\", \"flow\", \"clientId\", \"redirectUrl\", \"scopes\"].map(\n (name) => q.selectField(name, q.field(\"app\", name))\n ),\n }),\n ...([\"OAuthConnection\", \"ApiKeyConnection\", \"ExternalSessionConnection\"] as const).map((objectType) =>\n q.sub(objectType, {\n from: { source: { objectType }, binding: \"c\" },\n select: [\n \"id\",\n \"title\",\n \"userId\",\n \"status\",\n ...(objectType === \"OAuthConnection\"\n ? [\"application\", \"accessTokenExpiresAt\"]\n : [\"serviceInstance\", \"expiresAt\"]),\n ].map((name) => q.selectField(name, q.field(\"c\", name))),\n })\n ),\n ],\n};\nexport const connectPublicOntologyIR: OntologyIR = {\n ...connectOntology,\n policy: {\n objects: read,\n actions: connectOntology.actionTypes.map((action) => ({\n actionType: action.name,\n check:\n action.name === \"
|
|
1
|
+
{"version":3,"file":"publicOntology.js","names":[],"sources":["../src/publicOntology.ts"],"sourcesContent":["import * as q from \"@party-stack/ontology-spec/query\";\nimport { connectOntology } from \"./spec/index.js\";\nimport type { ConnectManagerService } from \"./makeConnectManager.js\";\nimport type { OntologyIR } from \"@party-stack/ontology-spec\";\n\n/** Device-local public view. It exposes inventory and authentication actions while\n * retaining token ciphertext and PKCE records at the credential owner. Public servers\n * must additionally scope instances/connections to their authenticated caller.\n */\nconst read = {\n select: [\n q.sub(\"services\", {\n from: { source: { objectType: \"ServiceInstance\" }, binding: \"s\" },\n select: [\"id\", \"title\", \"service\", \"instanceUrl\"].map((name) =>\n q.selectField(name, q.field(\"s\", name))\n ),\n }),\n q.sub(\"applications\", {\n from: { source: { objectType: \"OAuthApplication\" }, binding: \"app\" },\n select: [\"id\", \"title\", \"serviceInstance\", \"flow\", \"clientId\", \"redirectUrl\", \"scopes\"].map(\n (name) => q.selectField(name, q.field(\"app\", name))\n ),\n }),\n ...([\"OAuthConnection\", \"ApiKeyConnection\", \"ExternalSessionConnection\"] as const).map((objectType) =>\n q.sub(objectType, {\n from: { source: { objectType }, binding: \"c\" },\n select: [\n \"id\",\n \"title\",\n \"userId\",\n \"status\",\n ...(objectType === \"OAuthConnection\"\n ? [\"application\", \"accessTokenExpiresAt\"]\n : [\"serviceInstance\", \"expiresAt\"]),\n ].map((name) => q.selectField(name, q.field(\"c\", name))),\n })\n ),\n ],\n};\nexport const connectPublicOntologyIR: OntologyIR = {\n ...connectOntology,\n policy: {\n objects: read,\n actions: connectOntology.actionTypes.map((action) => ({\n actionType: action.name,\n check:\n // The connection manager owns renewal and shares it across requests. A client\n // refreshing directly would race it and leave its requests failing with Conflict.\n action.name === \"refreshConnection\"\n ? q.literal(false)\n : action.name === \"beginAuthorization\"\n ? q.exists({\n from: { source: { objectType: \"OAuthApplication\" }, binding: \"app\" },\n where: q.and(\n q.eq(q.field(\"app\", \"id\"), q.input(\"applicationId\")),\n q.eq(q.field(\"app\", \"redirectUrl\"), q.input(\"redirectUrl\"))\n ),\n })\n : q.literal(true),\n })),\n },\n};\n\n/** Private device ports share an account inventory. A public server must instead\n * bind a caller-specific policy/context; this policy hides secrets but not accounts.\n * Keep the current generic executor behind this composition until owned workflows\n * provide its multi-transaction action lifecycle.\n */\nexport function connectDeviceRoute(manager: Pick<ConnectManagerService, \"backend\">) {\n return {\n kind: \"proxy\" as const,\n backend: manager.backend,\n ir: connectPublicOntologyIR,\n context: {},\n };\n}\n"],"mappings":";;;;;;;AASA,MAAM,OAAO,EACT,QAAQ;CACJ,EAAE,IAAI,YAAY;EACd,MAAM;GAAE,QAAQ,EAAE,YAAY,kBAAkB;GAAG,SAAS;EAAI;EAChE,QAAQ;GAAC;GAAM;GAAS;GAAW;EAAa,CAAC,CAAC,KAAK,SACnD,EAAE,YAAY,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC,CAC1C;CACJ,CAAC;CACD,EAAE,IAAI,gBAAgB;EAClB,MAAM;GAAE,QAAQ,EAAE,YAAY,mBAAmB;GAAG,SAAS;EAAM;EACnE,QAAQ;GAAC;GAAM;GAAS;GAAmB;GAAQ;GAAY;GAAe;EAAQ,CAAC,CAAC,KACnF,SAAS,EAAE,YAAY,MAAM,EAAE,MAAM,OAAO,IAAI,CAAC,CACtD;CACJ,CAAC;CACD,GAAI;EAAC;EAAmB;EAAoB;CAA2B,CAAC,CAAW,KAAK,eACpF,EAAE,IAAI,YAAY;EACd,MAAM;GAAE,QAAQ,EAAE,WAAW;GAAG,SAAS;EAAI;EAC7C,QAAQ;GACJ;GACA;GACA;GACA;GACA,GAAI,eAAe,oBACb,CAAC,eAAe,sBAAsB,IACtC,CAAC,mBAAmB,WAAW;EACzC,CAAC,CAAC,KAAK,SAAS,EAAE,YAAY,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC,CAAC;CAC3D,CAAC,CACL;AACJ,EACJ;AACA,MAAa,0BAAsC;CAC/C,GAAG;CACH,QAAQ;EACJ,SAAS;EACT,SAAS,gBAAgB,YAAY,KAAK,YAAY;GAClD,YAAY,OAAO;GACnB,OAGI,OAAO,SAAS,sBACV,EAAE,QAAQ,KAAK,IACf,OAAO,SAAS,uBACd,EAAE,OAAO;IACL,MAAM;KAAE,QAAQ,EAAE,YAAY,mBAAmB;KAAG,SAAS;IAAM;IACnE,OAAO,EAAE,IACL,EAAE,GAAG,EAAE,MAAM,OAAO,IAAI,GAAG,EAAE,MAAM,eAAe,CAAC,GACnD,EAAE,GAAG,EAAE,MAAM,OAAO,aAAa,GAAG,EAAE,MAAM,aAAa,CAAC,CAC9D;GACJ,CAAC,IACD,EAAE,QAAQ,IAAI;EAC9B,EAAE;CACN;AACJ;;;;;;AAOA,SAAgB,mBAAmB,SAAiD;CAChF,OAAO;EACH,MAAM;EACN,SAAS,QAAQ;EACjB,IAAI;EACJ,SAAS,CAAC;CACd;AACJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serviceConnections.d.ts","names":[],"sources":["../src/serviceConnections.ts"],"mappings":";;;;;;;;;;iBAsBiB;WACJ,YAAY;WACZ;WACA,iBAAiB;WACjB,QAAQ;;WAER,gBAAgB;;;;;qBAsChB,yBAAsB;WACb,SAAA;WACF,OAAA;WACG,mBAAS;WACR,WAAA;;
|
|
1
|
+
{"version":3,"file":"serviceConnections.d.ts","names":[],"sources":["../src/serviceConnections.ts"],"mappings":";;;;;;;;;;iBAsBiB;WACJ,YAAY;WACZ;WACA,iBAAiB;WACjB,QAAQ;;WAER,gBAAgB;;;;;qBAsChB,yBAAsB;WACb,SAAA;WACF,OAAA;WACG,mBAAS;WACR,WAAA;;EAyeM,UAAA,YAAA,kBAAa,OAAA;;;;;;IAPS,iBAAA;;;;GASlD,6DAAA"}
|
|
@@ -2,7 +2,7 @@ import { connectOntology } from "./spec/index.js";
|
|
|
2
2
|
import { connectError } from "./core/errors.js";
|
|
3
3
|
import { connectBackendError } from "./core/backend.js";
|
|
4
4
|
import { createDefaultConnectionEgressHandlers } from "./createDefaultConnectionEgressHandlers.js";
|
|
5
|
-
import { connectionAccessToken } from "./core/accessToken.js";
|
|
5
|
+
import { accessTokenNeedsRefresh, connectionAccessToken } from "./core/accessToken.js";
|
|
6
6
|
import { BackendError, classifyBackendFailure, isUnauthenticatedError } from "@party-stack/ontology-backend";
|
|
7
7
|
import { Clock, Context, Effect, Fiber, Queue, RcMap, Schedule, Schema, Semaphore, Stream } from "effect";
|
|
8
8
|
import * as q from "@party-stack/ontology-spec/query";
|
|
@@ -26,7 +26,7 @@ const renewalUnavailable = (cause) => new BackendError({
|
|
|
26
26
|
kind: "Unavailable",
|
|
27
27
|
retryable: true,
|
|
28
28
|
actionOutcome: "not-committed",
|
|
29
|
-
message: "The
|
|
29
|
+
message: "The credential could not be renewed yet; retry the request.",
|
|
30
30
|
cause
|
|
31
31
|
});
|
|
32
32
|
/** Acquire saved identity and egress from ontology records. The map holds only
|
|
@@ -79,43 +79,22 @@ const makeServiceConnections = Effect.fn("Connect.connections")(function* (optio
|
|
|
79
79
|
retryable: false,
|
|
80
80
|
message: "Service connector is unavailable."
|
|
81
81
|
});
|
|
82
|
-
const
|
|
83
|
-
const currentCredential = Effect.fnUntraced(function* () {
|
|
82
|
+
const currentCredential = Effect.fnUntraced(function* (renewEarly = true) {
|
|
84
83
|
const current = yield* read(ref.objectType, ref.id);
|
|
85
84
|
if (!current || current.status === "inactive") return yield* unavailable("The selected connection is disconnected.");
|
|
86
85
|
if (current.status !== "active") return yield* unavailable("The selected connection requires authentication.");
|
|
87
|
-
if (ref.objectType === "OAuthConnection")
|
|
86
|
+
if (ref.objectType === "OAuthConnection") {
|
|
87
|
+
if (renewEarly && accessTokenNeedsRefresh(current, yield* Clock.currentTimeMillis)) {
|
|
88
|
+
yield* renew(credentialGeneration);
|
|
89
|
+
return yield* currentCredential(false);
|
|
90
|
+
}
|
|
91
|
+
return yield* connectionAccessToken(backend, ref.id, { refresh: false });
|
|
92
|
+
}
|
|
88
93
|
const expiresAt = current.expiresAt;
|
|
89
94
|
if (ref.objectType === "ExternalSessionConnection") {
|
|
90
95
|
(yield* CredentialObserver)(credentialVersion(current));
|
|
91
96
|
if (expiresAt && expiresAt.epochMilliseconds <= (yield* Clock.currentTimeMillis)) {
|
|
92
|
-
yield*
|
|
93
|
-
const selected = yield* options.store.get("ExternalSessionConnection", ref.id);
|
|
94
|
-
if (!selected || selected.status !== "active" || !selected.expiresAt || selected.expiresAt.epochMilliseconds > (yield* Clock.currentTimeMillis)) return;
|
|
95
|
-
if (!service.externalSession) return yield* new BackendError({
|
|
96
|
-
operation: "connect.session.verify",
|
|
97
|
-
kind: "InvalidConfiguration",
|
|
98
|
-
retryable: false,
|
|
99
|
-
message: "This service cannot verify an external session."
|
|
100
|
-
});
|
|
101
|
-
(yield* CredentialObserver)(credentialVersion(selected));
|
|
102
|
-
const verified = yield* Effect.result(service.externalSession({
|
|
103
|
-
serviceInstance,
|
|
104
|
-
sessionId: selected.sessionId
|
|
105
|
-
}));
|
|
106
|
-
yield* options.store.transaction(Effect.gen(function* () {
|
|
107
|
-
const latest = yield* options.store.get("ExternalSessionConnection", ref.id);
|
|
108
|
-
if (!latest || credentialVersion(latest) !== credentialVersion(selected)) return;
|
|
109
|
-
if (verified._tag === "Failure") return yield* verified.failure;
|
|
110
|
-
const identity = verified.success;
|
|
111
|
-
if (identity.userId !== selected.userId || identity.expiresAt && identity.expiresAt.epochMilliseconds <= (yield* Clock.currentTimeMillis)) return yield* connectError("NeedsAuthentication", "The selected external session requires authentication.");
|
|
112
|
-
yield* options.store.put("ExternalSessionConnection", {
|
|
113
|
-
...latest,
|
|
114
|
-
title: identity.title ?? latest.title,
|
|
115
|
-
expiresAt: identity.expiresAt
|
|
116
|
-
});
|
|
117
|
-
}));
|
|
118
|
-
})).pipe(Effect.mapError((error) => error instanceof BackendError ? error : connectBackendError(error)));
|
|
97
|
+
yield* renew(credentialGeneration, "expiring");
|
|
119
98
|
return yield* currentCredential();
|
|
120
99
|
}
|
|
121
100
|
return current.sessionId;
|
|
@@ -247,16 +226,57 @@ const makeServiceConnections = Effect.fn("Connect.connections")(function* (optio
|
|
|
247
226
|
if (isUnauthenticatedError(error)) yield* markNeedsAuthentication(observed);
|
|
248
227
|
return yield* error;
|
|
249
228
|
});
|
|
229
|
+
const verifyExternalSession = Effect.gen(function* () {
|
|
230
|
+
const selected = yield* options.store.get("ExternalSessionConnection", ref.id);
|
|
231
|
+
if (!selected || selected.status !== "active" || !selected.expiresAt || selected.expiresAt.epochMilliseconds > (yield* Clock.currentTimeMillis)) return;
|
|
232
|
+
if (!service.externalSession) return yield* new BackendError({
|
|
233
|
+
operation: "connect.session.verify",
|
|
234
|
+
kind: "InvalidConfiguration",
|
|
235
|
+
retryable: false,
|
|
236
|
+
message: "This service cannot verify an external session."
|
|
237
|
+
});
|
|
238
|
+
(yield* CredentialObserver)(credentialVersion(selected));
|
|
239
|
+
const verified = yield* Effect.result(service.externalSession({
|
|
240
|
+
serviceInstance,
|
|
241
|
+
sessionId: selected.sessionId
|
|
242
|
+
}));
|
|
243
|
+
yield* options.store.transaction(Effect.gen(function* () {
|
|
244
|
+
const latest = yield* options.store.get("ExternalSessionConnection", ref.id);
|
|
245
|
+
if (!latest || credentialVersion(latest) !== credentialVersion(selected)) return;
|
|
246
|
+
if (verified._tag === "Failure") return yield* verified.failure;
|
|
247
|
+
const identity = verified.success;
|
|
248
|
+
if (identity.userId !== selected.userId || identity.expiresAt && identity.expiresAt.epochMilliseconds <= (yield* Clock.currentTimeMillis)) return yield* connectError("NeedsAuthentication", "The selected external session requires authentication.");
|
|
249
|
+
yield* options.store.put("ExternalSessionConnection", {
|
|
250
|
+
...latest,
|
|
251
|
+
title: identity.title ?? latest.title,
|
|
252
|
+
expiresAt: identity.expiresAt
|
|
253
|
+
});
|
|
254
|
+
}));
|
|
255
|
+
}).pipe(Effect.mapError((error) => error instanceof BackendError ? error : connectBackendError(error)));
|
|
250
256
|
const renewal = yield* Semaphore.make(1);
|
|
251
257
|
let renewals = 0;
|
|
252
258
|
let failedRenewal;
|
|
253
|
-
const renew = (version) => Effect.suspend(() => {
|
|
259
|
+
const renew = (version, reason = "rejected") => Effect.suspend(() => {
|
|
254
260
|
const waitingSince = renewals;
|
|
255
261
|
return renewal.withPermit(Effect.gen(function* () {
|
|
256
262
|
if (version !== credentialGeneration) return;
|
|
257
263
|
if (failedRenewal?.version === version && failedRenewal.attempt > waitingSince) return yield* failedRenewal.error;
|
|
258
264
|
const current = yield* read(ref.objectType, ref.id);
|
|
259
265
|
if (current?.status !== "active") return;
|
|
266
|
+
if (ref.objectType === "ExternalSessionConnection" && reason === "expiring") {
|
|
267
|
+
const result = yield* Effect.result(verifyExternalSession);
|
|
268
|
+
install(yield* read(ref.objectType, ref.id));
|
|
269
|
+
if (result._tag === "Failure") {
|
|
270
|
+
failedRenewal = {
|
|
271
|
+
version,
|
|
272
|
+
attempt: ++renewals,
|
|
273
|
+
error: result.failure
|
|
274
|
+
};
|
|
275
|
+
return yield* result.failure;
|
|
276
|
+
}
|
|
277
|
+
renewals++;
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
260
280
|
if (ref.objectType !== "OAuthConnection") {
|
|
261
281
|
yield* markNeedsAuthentication(credentialVersion(current));
|
|
262
282
|
return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serviceConnections.js","names":[],"sources":["../src/serviceConnections.ts"],"sourcesContent":["import { BackendError, classifyBackendFailure, isUnauthenticatedError } from \"@party-stack/ontology-backend\";\nimport * as q from \"@party-stack/ontology-spec/query\";\nimport { Clock, Context, Effect, Fiber, Queue, RcMap, Schema, Stream, Schedule, Semaphore } from \"effect\";\nimport { connectionAccessToken } from \"./core/accessToken.js\";\nimport { connectBackendError } from \"./core/backend.js\";\nimport { connectError } from \"./core/errors.js\";\nimport { createDefaultConnectionEgressHandlers } from \"./createDefaultConnectionEgressHandlers.js\";\nimport { connectOntology } from \"./spec/index.js\";\nimport type { ConnectStore } from \"./core/store.js\";\nimport type { ConnectionRef, SavedConnection, ServiceConnector } from \"./ServiceConnector.js\";\nimport type { ConnectOntology, ServiceInstanceRecord } from \"./spec/index.js\";\nimport type {\n ConnectionEgress,\n ConnectionEgressHandlers,\n ConnectionLifecycle,\n ConnectionState,\n} from \"./types.js\";\nimport type { OntologyBackendService } from \"@party-stack/ontology-backend\";\n\n/** Scoped identity and egress for one saved connection. Cached data can reopen\n * while authentication is required; actual egress always requires active credentials.\n */\nexport interface ConnectionAccess {\n readonly connection: ConnectionRef;\n readonly userId: string;\n readonly serviceInstance: ServiceInstanceRecord;\n readonly egress: ConnectionEgress;\n /** Pass to the replica that syncs this connection; show apps only its monitor fields. */\n readonly authentication: ConnectionLifecycle;\n}\n\nconst unavailable = (message: string) =>\n new BackendError({\n operation: \"connect.acquire\",\n kind: \"Unauthenticated\",\n retryable: false,\n message,\n });\n\n// Observe the credential actually used by this request, including renewal. A\n// later rejection must not change the status of a newer saved session.\nconst CredentialObserver = Context.Reference<(version: string) => void>(\n \"@party-stack/connect/CredentialObserver\",\n { defaultValue: () => () => {} }\n);\nconst retryAfterRenewal = () =>\n new BackendError({\n operation: \"connect.egress\",\n kind: \"Unavailable\",\n retryable: true,\n actionOutcome: \"not-committed\",\n message: \"The credential was renewed after the service rejected it; retry the request.\",\n });\nconst renewalUnavailable = (cause: BackendError) =>\n new BackendError({\n operation: \"connect.refresh\",\n kind: \"Unavailable\",\n retryable: true,\n actionOutcome: \"not-committed\",\n message: \"The rejected credential could not be renewed yet; retry the request.\",\n cause,\n });\n\n/** Acquire saved identity and egress from ontology records. The map holds only\n * scoped access; the Connect backend remains the sole durable inventory.\n */\nexport const makeServiceConnections = Effect.fn(\"Connect.connections\")(function* (options: {\n readonly backend: OntologyBackendService;\n readonly store: ConnectStore;\n readonly services: readonly ServiceConnector[];\n readonly handlers?: ConnectionEgressHandlers;\n}) {\n const backend = options.backend;\n const services = new Map(options.services.map((service) => [service.service, service]));\n if (services.size !== options.services.length)\n return yield* new BackendError({\n operation: \"connect.configure\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"Service connector names must be unique.\",\n });\n const read = Effect.fnUntraced(function* <N extends keyof ConnectOntology[\"objectTypes\"]>(\n objectType: N,\n id: string\n ) {\n const rows = yield* backend.query({\n select: [\n q.sub(\"rows\", {\n from: { source: { objectType }, binding: \"row\" },\n where: q.eq(q.field(\"row\", \"id\"), q.literal(id)),\n select: connectOntology.objectTypes\n .find((type) => type.name === objectType)!\n .properties.map((property) =>\n q.selectField(property.name, q.field(\"row\", property.name))\n ),\n }),\n ],\n });\n return (rows.rows as ConnectOntology[\"objectTypes\"][N][])[0];\n });\n const reference = Schema.Struct({\n objectType: Schema.Literals([\"OAuthConnection\", \"ApiKeyConnection\", \"ExternalSessionConnection\"]),\n id: Schema.NonEmptyString,\n });\n const codec = Schema.fromJsonString(reference);\n const access = yield* RcMap.make({\n lookup: Effect.fnUntraced(function* (key: string) {\n const ref = yield* Schema.decodeUnknownEffect(codec)(key).pipe(\n Effect.mapError((cause) => classifyBackendFailure(\"connect.acquire\", cause))\n );\n const row = yield* read(ref.objectType, ref.id);\n if (!row || row.status === \"inactive\" || !row.userId)\n return yield* unavailable(\"The selected connection is disconnected.\");\n const instanceId =\n ref.objectType === \"OAuthConnection\"\n ? (yield* read(\n \"OAuthApplication\",\n (row as ConnectOntology[\"objectTypes\"][\"OAuthConnection\"]).application\n ))?.serviceInstance\n : (\n row as\n | ConnectOntology[\"objectTypes\"][\"ApiKeyConnection\"]\n | ConnectOntology[\"objectTypes\"][\"ExternalSessionConnection\"]\n ).serviceInstance;\n const serviceInstance = instanceId ? yield* read(\"ServiceInstance\", instanceId) : undefined;\n if (!serviceInstance)\n return yield* new BackendError({\n operation: \"connect.acquire\",\n kind: \"NotFound\",\n retryable: false,\n message: \"Service instance is unavailable.\",\n });\n const service = services.get(serviceInstance.service);\n if (!service)\n return yield* new BackendError({\n operation: \"connect.acquire\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"Service connector is unavailable.\",\n });\n const sessionVerification = yield* Semaphore.make(1);\n const currentCredential = Effect.fnUntraced(function* (): Effect.fn.Return<string, BackendError> {\n const current = yield* read(ref.objectType, ref.id);\n if (!current || current.status === \"inactive\")\n return yield* unavailable(\"The selected connection is disconnected.\");\n if (current.status !== \"active\")\n return yield* unavailable(\"The selected connection requires authentication.\");\n if (ref.objectType === \"OAuthConnection\")\n return yield* connectionAccessToken(backend, ref.id);\n const expiresAt = (\n current as\n | ConnectOntology[\"objectTypes\"][\"ExternalSessionConnection\"]\n | ConnectOntology[\"objectTypes\"][\"ApiKeyConnection\"]\n ).expiresAt;\n if (ref.objectType === \"ExternalSessionConnection\") {\n (yield* CredentialObserver)(credentialVersion(current));\n if (expiresAt && expiresAt.epochMilliseconds <= (yield* Clock.currentTimeMillis)) {\n yield* sessionVerification\n .withPermit(\n Effect.gen(function* () {\n const selected = yield* options.store.get(\n \"ExternalSessionConnection\",\n ref.id\n );\n if (\n !selected ||\n selected.status !== \"active\" ||\n !selected.expiresAt ||\n selected.expiresAt.epochMilliseconds >\n (yield* Clock.currentTimeMillis)\n )\n return;\n if (!service.externalSession)\n return yield* new BackendError({\n operation: \"connect.session.verify\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"This service cannot verify an external session.\",\n });\n (yield* CredentialObserver)(credentialVersion(selected));\n const verified = yield* Effect.result(\n service.externalSession({\n serviceInstance,\n sessionId: selected.sessionId,\n })\n );\n yield* options.store.transaction(\n Effect.gen(function* () {\n const latest = yield* options.store.get(\n \"ExternalSessionConnection\",\n ref.id\n );\n if (\n !latest ||\n credentialVersion(latest) !== credentialVersion(selected)\n )\n return;\n if (verified._tag === \"Failure\") return yield* verified.failure;\n const identity = verified.success;\n if (\n identity.userId !== selected.userId ||\n (identity.expiresAt &&\n identity.expiresAt.epochMilliseconds <=\n (yield* Clock.currentTimeMillis))\n )\n return yield* connectError(\n \"NeedsAuthentication\",\n \"The selected external session requires authentication.\"\n );\n yield* options.store.put(\"ExternalSessionConnection\", {\n ...latest,\n title: identity.title ?? latest.title,\n expiresAt: identity.expiresAt,\n });\n })\n );\n })\n )\n .pipe(\n Effect.mapError((error) =>\n error instanceof BackendError ? error : connectBackendError(error)\n )\n );\n return yield* currentCredential();\n }\n return (current as ConnectOntology[\"objectTypes\"][\"ExternalSessionConnection\"]).sessionId;\n }\n if (expiresAt && expiresAt.epochMilliseconds <= (yield* Clock.currentTimeMillis))\n return yield* unavailable(\"The selected connection has expired.\");\n const apiKey = (current as ConnectOntology[\"objectTypes\"][\"ApiKeyConnection\"]).apiKey;\n if (!apiKey || !backend.encrypted) return yield* unavailable(\"API key is unavailable.\");\n const result = yield* backend.encrypted.decrypt({\n ...apiKey,\n source: { objectType: ref.objectType, primaryKey: ref.id, property: \"apiKey\" },\n });\n return yield* Schema.decodeUnknownEffect(Schema.String)(result.value).pipe(\n Effect.mapError((cause) => classifyBackendFailure(\"connect.credential\", cause))\n );\n });\n let state: ConnectionState = { status: row.status };\n let fingerprint = JSON.stringify(row);\n const credentialVersion = (value: typeof row | undefined) =>\n JSON.stringify(\n !value\n ? null\n : [\n value.status,\n value.userId,\n \"application\" in value\n ? [\n value.application,\n value.accessToken?.ciphertext,\n value.refreshToken?.ciphertext,\n value.operationId,\n ]\n : \"sessionId\" in value\n ? [value.serviceInstance, value.sessionId, value.expiresAt]\n : [value.serviceInstance, value.apiKey?.ciphertext, value.expiresAt],\n ]\n );\n const listeners = new Set<(state: ConnectionState) => void>();\n const publish = (value: ConnectionState, changedCredential = false) => {\n if (!changedCredential && JSON.stringify(state) === JSON.stringify(value)) return;\n state = value;\n for (const listener of listeners) listener(value);\n };\n // The credential itself, not bookkeeping such as an in-progress refresh marker:\n // only a new credential (or a status change) is a new activation.\n const credentialIdentity = (value: typeof row | undefined) =>\n JSON.stringify(\n !value\n ? null\n : [\n value.status,\n value.userId,\n \"application\" in value\n ? value.accessToken?.ciphertext\n : \"sessionId\" in value\n ? [value.sessionId, value.expiresAt]\n : [value.apiKey?.ciphertext, value.expiresAt],\n ]\n );\n let credentialGeneration = 0;\n let credential = credentialIdentity(row);\n const install = (value: typeof row | undefined) => {\n const next = JSON.stringify(value);\n const changed = fingerprint !== next;\n fingerprint = next;\n const nextCredential = credentialIdentity(value);\n const renewed = nextCredential !== credential;\n credential = nextCredential;\n if (renewed) credentialGeneration++;\n if (changed || state.status === \"error\")\n publish({ status: value?.status ?? \"inactive\" }, renewed);\n };\n const watch =\n backend.changes?.watch ??\n backend.watchSubset?.({\n from: { source: { objectType: ref.objectType }, binding: \"connection\" },\n where: q.eq(q.field(\"connection\", \"id\"), q.literal(ref.id)),\n });\n if (watch)\n yield* Stream.runForEach(\n Stream.unwrap(\n watch.pipe(\n // Acquisition has registered and buffered the feed. Re-read\n // after every acquisition, including a retry, before consuming hints.\n Effect.tap(() =>\n read(ref.objectType, ref.id).pipe(\n Effect.tap((value) => Effect.sync(() => install(value)))\n )\n )\n )\n ),\n () =>\n read(ref.objectType, ref.id).pipe(\n Effect.tap((value) => Effect.sync(() => install(value)))\n )\n ).pipe(\n Effect.scoped,\n Effect.tapError((error) =>\n Effect.sync(() => publish({ status: \"error\", error: error.message }))\n ),\n Effect.retry({ schedule: Schedule.spaced(1000), while: (error) => error.retryable }),\n Effect.catch((error) => Effect.logError(\"Connection watch stopped\", error)),\n Effect.forkScoped({ startImmediately: true })\n );\n // Supply a current value while background watch acquisition is pending;\n // the acquisition path repeats this read after registration.\n yield* read(ref.objectType, ref.id).pipe(\n Effect.tap((value) => Effect.sync(() => install(value)))\n );\n const monitor = {\n changes: Stream.callback<ConnectionState>(\n (queue) =>\n Effect.acquireRelease(\n Effect.sync(() => {\n const send = (next: ConnectionState) => {\n Queue.offerUnsafe(queue, next);\n };\n listeners.add(send);\n send(state);\n return send;\n }),\n (send) =>\n Effect.sync(() => {\n listeners.delete(send);\n })\n ),\n { bufferSize: 1, strategy: \"sliding\" }\n ),\n };\n const handlers = options.handlers ?? createDefaultConnectionEgressHandlers();\n const sockets = new Set<WebSocket>();\n const lifetime = new AbortController();\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => {\n listeners.clear();\n lifetime.abort();\n for (const socket of sockets) socket.close();\n sockets.clear();\n })\n );\n const acquired = yield* service.acquire({\n connection: { objectType: ref.objectType, value: row } as SavedConnection,\n serviceInstance,\n credential: currentCredential(),\n handlers: {\n fetch: (request) =>\n handlers.fetch(\n new Request(request, {\n signal: AbortSignal.any([request.signal, lifetime.signal]),\n })\n ),\n createWebSocket: Effect.fnUntraced(function* (\n url: string | URL,\n protocols?: string | string[]\n ) {\n const socket = yield* handlers.createWebSocket(url, protocols);\n if (lifetime.signal.aborted) {\n socket.close();\n return yield* unavailable(\"The selected connection was released.\");\n }\n sockets.add(socket);\n socket.addEventListener(\"close\", () => sockets.delete(socket), { once: true });\n return socket;\n }),\n },\n });\n const scope = yield* Effect.scope;\n const owned = <A>(work: Effect.Effect<A, BackendError>) =>\n Effect.suspend(() =>\n scope.state._tag === \"Closed\"\n ? Effect.fail(unavailable(\"The selected connection was released.\"))\n : Effect.acquireUseRelease(Effect.forkIn(work, scope), Fiber.join, Fiber.interrupt)\n );\n // Compare and persist in one transaction: a late rejection must neither\n // pause a newer login nor resurrect a disconnected row. The ordinary\n // journal/watch path also updates account queries.\n const markNeedsAuthentication = (observed: string | undefined) =>\n options.store\n .transaction(\n Effect.gen(function* () {\n const current = yield* options.store.get(ref.objectType, ref.id);\n if (current?.status === \"active\" && credentialVersion(current) === observed)\n yield* options.store.put(ref.objectType, {\n ...current,\n status: \"needs-auth\",\n });\n })\n )\n .pipe(\n Effect.mapError(connectBackendError),\n Effect.tapError((cause) =>\n Effect.logError(\"Could not save connection authentication status\", cause)\n ),\n Effect.ignore,\n Effect.uninterruptible\n );\n const failed = Effect.fnUntraced(function* (error: BackendError, observed: string | undefined) {\n if (isUnauthenticatedError(error)) yield* markNeedsAuthentication(observed);\n return yield* error;\n });\n const renewal = yield* Semaphore.make(1);\n // Renew the credential that was saved at `version`, once: concurrent rejections\n // of the same credential share one renewal, and a newer credential wins.\n // Rejections queued behind a renewal that failed share its failure instead of\n // each asking the provider again; a rejection after it tries again.\n let renewals = 0;\n let failedRenewal: { version: number; attempt: number; error: BackendError } | undefined;\n const renew = (version: number) =>\n Effect.suspend(() => {\n const waitingSince = renewals;\n return renewal.withPermit(\n Effect.gen(function* () {\n if (version !== credentialGeneration) return;\n if (failedRenewal?.version === version && failedRenewal.attempt > waitingSince)\n return yield* failedRenewal.error;\n const current = yield* read(ref.objectType, ref.id);\n if (current?.status !== \"active\") return;\n if (ref.objectType !== \"OAuthConnection\") {\n yield* markNeedsAuthentication(credentialVersion(current));\n return;\n }\n const result = yield* Effect.result(\n backend.applyAction({\n id: crypto.randomUUID(),\n name: \"refreshConnection\",\n parameters: { connectionId: ref.id },\n })\n );\n // Publish now rather than when the row watch catches up, so a\n // concurrent rejection of the old credential does not renew again.\n install(yield* read(ref.objectType, ref.id));\n // A refresh token that no longer works already moved the\n // connection to needs-auth; anything else may succeed later.\n if (result._tag === \"Failure\" && !isUnauthenticatedError(result.failure)) {\n const error = renewalUnavailable(result.failure);\n failedRenewal = { version, attempt: ++renewals, error };\n return yield* error;\n }\n renewals++;\n })\n );\n });\n const requireAuthentication = Effect.fnUntraced(function* () {\n const current = yield* read(ref.objectType, ref.id);\n if (!current || current.status === \"inactive\")\n return yield* unavailable(\"The selected connection is disconnected.\");\n if (current.status !== \"active\")\n return yield* unavailable(\"The selected connection requires authentication.\");\n return current;\n });\n const egress: ConnectionEgress = {\n fetch: (input, init) =>\n owned(\n Effect.gen(function* () {\n const version = credentialGeneration;\n let observed = credentialVersion(yield* requireAuthentication());\n const request = yield* Effect.try({\n try: () => new Request(input, init),\n catch: (cause) => classifyBackendFailure(\"connect.egress.fetch\", cause),\n });\n // Only a request without a body is sent again after a renewal. A body\n // can be a one-shot stream (a proxied upload); the outbox or sync\n // retries those after the renewal instead.\n const replay = request.body === null ? request.clone() : undefined;\n const send = (value: Request) =>\n acquired.fetch(value).pipe(\n Effect.provideService(CredentialObserver, (value) => {\n observed = value;\n })\n );\n const first = yield* Effect.result(send(request));\n if (first._tag === \"Success\") return first.success;\n if (\n !isUnauthenticatedError(first.failure) ||\n ref.objectType !== \"OAuthConnection\"\n )\n return yield* failed(first.failure, observed);\n yield* renew(version);\n if (state.status !== \"active\") return yield* first.failure;\n if (!replay) return yield* retryAfterRenewal();\n observed = credentialVersion(yield* requireAuthentication());\n return yield* send(replay).pipe(Effect.catch((error) => failed(error, observed)));\n })\n ),\n createWebSocket: (url, protocols) =>\n owned(\n Effect.gen(function* () {\n let observed = credentialVersion(yield* requireAuthentication());\n return yield* acquired.createWebSocket(url, protocols).pipe(\n Effect.provideService(CredentialObserver, (value) => {\n observed = value;\n }),\n Effect.catch((error) => failed(error, observed))\n );\n })\n ),\n };\n const authentication: ConnectionLifecycle = {\n get state() {\n return state;\n },\n changes: monitor.changes,\n get credentialVersion() {\n return credentialGeneration;\n },\n refresh: renew,\n };\n return {\n connection: ref,\n userId: row.userId,\n serviceInstance: serviceInstance as ServiceInstanceRecord,\n egress,\n authentication,\n } satisfies ConnectionAccess;\n }),\n });\n return {\n acquire: (connection: ConnectionRef) => RcMap.get(access, Schema.encodeSync(codec)(connection)),\n };\n});\n"],"mappings":";;;;;;;;;AA+BA,MAAM,eAAe,YACjB,IAAI,aAAa;CACb,WAAW;CACX,MAAM;CACN,WAAW;CACX;AACJ,CAAC;AAIL,MAAM,qBAAqB,QAAQ,UAC/B,2CACA,EAAE,0BAA0B,CAAC,EAAE,CACnC;AACA,MAAM,0BACF,IAAI,aAAa;CACb,WAAW;CACX,MAAM;CACN,WAAW;CACX,eAAe;CACf,SAAS;AACb,CAAC;AACL,MAAM,sBAAsB,UACxB,IAAI,aAAa;CACb,WAAW;CACX,MAAM;CACN,WAAW;CACX,eAAe;CACf,SAAS;CACT;AACJ,CAAC;;;;AAKL,MAA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ACjD,WAAW;IACf,CAAC,GACD,OAAO,OAAO,UAAU,OAAO,OAAO,QAAQ,CAAC,CACnD;GACJ,CAAC,CACL;EACR;EACA,MAAM,iBAAsC;GACxC,IAAI,QAAQ;IACR,OAAO;GACX;GACA,SAAS,QAAQ;GACjB,IAAI,oBAAoB;IACpB,OAAO;GACX;GACA,SAAS;EACb;EACA,OAAO;GACH,YAAY;GACZ,QAAQ,IAAI;GACK;GACjB;GACA;EACJ;CACJ,CAAC,EACL,CAAC;CACD,OAAO,EACH,UAAU,eAA8B,MAAM,IAAI,QAAQ,OAAO,WAAW,KAAK,CAAC,CAAC,UAAU,CAAC,EAClG;AACJ,CAAC"}
|
|
1
|
+
{"version":3,"file":"serviceConnections.js","names":[],"sources":["../src/serviceConnections.ts"],"sourcesContent":["import { BackendError, classifyBackendFailure, isUnauthenticatedError } from \"@party-stack/ontology-backend\";\nimport * as q from \"@party-stack/ontology-spec/query\";\nimport { Clock, Context, Effect, Fiber, Queue, RcMap, Schema, Stream, Schedule, Semaphore } from \"effect\";\nimport { accessTokenNeedsRefresh, connectionAccessToken } from \"./core/accessToken.js\";\nimport { connectBackendError } from \"./core/backend.js\";\nimport { connectError } from \"./core/errors.js\";\nimport { createDefaultConnectionEgressHandlers } from \"./createDefaultConnectionEgressHandlers.js\";\nimport { connectOntology } from \"./spec/index.js\";\nimport type { ConnectStore } from \"./core/store.js\";\nimport type { ConnectionRef, SavedConnection, ServiceConnector } from \"./ServiceConnector.js\";\nimport type { ConnectOntology, ServiceInstanceRecord } from \"./spec/index.js\";\nimport type {\n ConnectionEgress,\n ConnectionEgressHandlers,\n ConnectionLifecycle,\n ConnectionState,\n} from \"./types.js\";\nimport type { OntologyBackendService } from \"@party-stack/ontology-backend\";\n\n/** Scoped identity and egress for one saved connection. Cached data can reopen\n * while authentication is required; actual egress always requires active credentials.\n */\nexport interface ConnectionAccess {\n readonly connection: ConnectionRef;\n readonly userId: string;\n readonly serviceInstance: ServiceInstanceRecord;\n readonly egress: ConnectionEgress;\n /** Pass to the replica that syncs this connection; show apps only its monitor fields. */\n readonly authentication: ConnectionLifecycle;\n}\n\nconst unavailable = (message: string) =>\n new BackendError({\n operation: \"connect.acquire\",\n kind: \"Unauthenticated\",\n retryable: false,\n message,\n });\n\n// Observe the credential actually used by this request, including renewal. A\n// later rejection must not change the status of a newer saved session.\nconst CredentialObserver = Context.Reference<(version: string) => void>(\n \"@party-stack/connect/CredentialObserver\",\n { defaultValue: () => () => {} }\n);\nconst retryAfterRenewal = () =>\n new BackendError({\n operation: \"connect.egress\",\n kind: \"Unavailable\",\n retryable: true,\n actionOutcome: \"not-committed\",\n message: \"The credential was renewed after the service rejected it; retry the request.\",\n });\nconst renewalUnavailable = (cause: BackendError) =>\n new BackendError({\n operation: \"connect.refresh\",\n kind: \"Unavailable\",\n retryable: true,\n actionOutcome: \"not-committed\",\n message: \"The credential could not be renewed yet; retry the request.\",\n cause,\n });\n\n/** Acquire saved identity and egress from ontology records. The map holds only\n * scoped access; the Connect backend remains the sole durable inventory.\n */\nexport const makeServiceConnections = Effect.fn(\"Connect.connections\")(function* (options: {\n readonly backend: OntologyBackendService;\n readonly store: ConnectStore;\n readonly services: readonly ServiceConnector[];\n readonly handlers?: ConnectionEgressHandlers;\n}) {\n const backend = options.backend;\n const services = new Map(options.services.map((service) => [service.service, service]));\n if (services.size !== options.services.length)\n return yield* new BackendError({\n operation: \"connect.configure\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"Service connector names must be unique.\",\n });\n const read = Effect.fnUntraced(function* <N extends keyof ConnectOntology[\"objectTypes\"]>(\n objectType: N,\n id: string\n ) {\n const rows = yield* backend.query({\n select: [\n q.sub(\"rows\", {\n from: { source: { objectType }, binding: \"row\" },\n where: q.eq(q.field(\"row\", \"id\"), q.literal(id)),\n select: connectOntology.objectTypes\n .find((type) => type.name === objectType)!\n .properties.map((property) =>\n q.selectField(property.name, q.field(\"row\", property.name))\n ),\n }),\n ],\n });\n return (rows.rows as ConnectOntology[\"objectTypes\"][N][])[0];\n });\n const reference = Schema.Struct({\n objectType: Schema.Literals([\"OAuthConnection\", \"ApiKeyConnection\", \"ExternalSessionConnection\"]),\n id: Schema.NonEmptyString,\n });\n const codec = Schema.fromJsonString(reference);\n const access = yield* RcMap.make({\n lookup: Effect.fnUntraced(function* (key: string) {\n const ref = yield* Schema.decodeUnknownEffect(codec)(key).pipe(\n Effect.mapError((cause) => classifyBackendFailure(\"connect.acquire\", cause))\n );\n const row = yield* read(ref.objectType, ref.id);\n if (!row || row.status === \"inactive\" || !row.userId)\n return yield* unavailable(\"The selected connection is disconnected.\");\n const instanceId =\n ref.objectType === \"OAuthConnection\"\n ? (yield* read(\n \"OAuthApplication\",\n (row as ConnectOntology[\"objectTypes\"][\"OAuthConnection\"]).application\n ))?.serviceInstance\n : (\n row as\n | ConnectOntology[\"objectTypes\"][\"ApiKeyConnection\"]\n | ConnectOntology[\"objectTypes\"][\"ExternalSessionConnection\"]\n ).serviceInstance;\n const serviceInstance = instanceId ? yield* read(\"ServiceInstance\", instanceId) : undefined;\n if (!serviceInstance)\n return yield* new BackendError({\n operation: \"connect.acquire\",\n kind: \"NotFound\",\n retryable: false,\n message: \"Service instance is unavailable.\",\n });\n const service = services.get(serviceInstance.service);\n if (!service)\n return yield* new BackendError({\n operation: \"connect.acquire\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"Service connector is unavailable.\",\n });\n const currentCredential = Effect.fnUntraced(function* (\n renewEarly = true\n ): Effect.fn.Return<string, BackendError> {\n const current = yield* read(ref.objectType, ref.id);\n if (!current || current.status === \"inactive\")\n return yield* unavailable(\"The selected connection is disconnected.\");\n if (current.status !== \"active\")\n return yield* unavailable(\"The selected connection requires authentication.\");\n if (ref.objectType === \"OAuthConnection\") {\n if (\n renewEarly &&\n accessTokenNeedsRefresh(\n current as ConnectOntology[\"objectTypes\"][\"OAuthConnection\"],\n yield* Clock.currentTimeMillis\n )\n ) {\n // Renew a token that is about to expire through the connection's one\n // renewal, like a rejected one. Requests queued behind it skip their own\n // refresh once the credential changes, even when the new token is also\n // short-lived, and share a failed attempt instead of each retrying it.\n yield* renew(credentialGeneration);\n return yield* currentCredential(false);\n }\n // This manager owns renewal; the helper only reads and decrypts.\n return yield* connectionAccessToken(backend, ref.id, { refresh: false });\n }\n const expiresAt = (\n current as\n | ConnectOntology[\"objectTypes\"][\"ExternalSessionConnection\"]\n | ConnectOntology[\"objectTypes\"][\"ApiKeyConnection\"]\n ).expiresAt;\n if (ref.objectType === \"ExternalSessionConnection\") {\n (yield* CredentialObserver)(credentialVersion(current));\n if (expiresAt && expiresAt.epochMilliseconds <= (yield* Clock.currentTimeMillis)) {\n // Verify through the connection's one renewal: requests that queued for\n // the same expired session share its answer instead of each asking again.\n yield* renew(credentialGeneration, \"expiring\");\n return yield* currentCredential();\n }\n return (current as ConnectOntology[\"objectTypes\"][\"ExternalSessionConnection\"]).sessionId;\n }\n if (expiresAt && expiresAt.epochMilliseconds <= (yield* Clock.currentTimeMillis))\n return yield* unavailable(\"The selected connection has expired.\");\n const apiKey = (current as ConnectOntology[\"objectTypes\"][\"ApiKeyConnection\"]).apiKey;\n if (!apiKey || !backend.encrypted) return yield* unavailable(\"API key is unavailable.\");\n const result = yield* backend.encrypted.decrypt({\n ...apiKey,\n source: { objectType: ref.objectType, primaryKey: ref.id, property: \"apiKey\" },\n });\n return yield* Schema.decodeUnknownEffect(Schema.String)(result.value).pipe(\n Effect.mapError((cause) => classifyBackendFailure(\"connect.credential\", cause))\n );\n });\n let state: ConnectionState = { status: row.status };\n let fingerprint = JSON.stringify(row);\n const credentialVersion = (value: typeof row | undefined) =>\n JSON.stringify(\n !value\n ? null\n : [\n value.status,\n value.userId,\n \"application\" in value\n ? [\n value.application,\n value.accessToken?.ciphertext,\n value.refreshToken?.ciphertext,\n value.operationId,\n ]\n : \"sessionId\" in value\n ? [value.serviceInstance, value.sessionId, value.expiresAt]\n : [value.serviceInstance, value.apiKey?.ciphertext, value.expiresAt],\n ]\n );\n const listeners = new Set<(state: ConnectionState) => void>();\n const publish = (value: ConnectionState, changedCredential = false) => {\n if (!changedCredential && JSON.stringify(state) === JSON.stringify(value)) return;\n state = value;\n for (const listener of listeners) listener(value);\n };\n // The credential itself, not bookkeeping such as an in-progress refresh marker:\n // only a new credential (or a status change) is a new activation.\n const credentialIdentity = (value: typeof row | undefined) =>\n JSON.stringify(\n !value\n ? null\n : [\n value.status,\n value.userId,\n \"application\" in value\n ? value.accessToken?.ciphertext\n : \"sessionId\" in value\n ? [value.sessionId, value.expiresAt]\n : [value.apiKey?.ciphertext, value.expiresAt],\n ]\n );\n let credentialGeneration = 0;\n let credential = credentialIdentity(row);\n const install = (value: typeof row | undefined) => {\n const next = JSON.stringify(value);\n const changed = fingerprint !== next;\n fingerprint = next;\n const nextCredential = credentialIdentity(value);\n const renewed = nextCredential !== credential;\n credential = nextCredential;\n if (renewed) credentialGeneration++;\n if (changed || state.status === \"error\")\n publish({ status: value?.status ?? \"inactive\" }, renewed);\n };\n const watch =\n backend.changes?.watch ??\n backend.watchSubset?.({\n from: { source: { objectType: ref.objectType }, binding: \"connection\" },\n where: q.eq(q.field(\"connection\", \"id\"), q.literal(ref.id)),\n });\n if (watch)\n yield* Stream.runForEach(\n Stream.unwrap(\n watch.pipe(\n // Acquisition has registered and buffered the feed. Re-read\n // after every acquisition, including a retry, before consuming hints.\n Effect.tap(() =>\n read(ref.objectType, ref.id).pipe(\n Effect.tap((value) => Effect.sync(() => install(value)))\n )\n )\n )\n ),\n () =>\n read(ref.objectType, ref.id).pipe(\n Effect.tap((value) => Effect.sync(() => install(value)))\n )\n ).pipe(\n Effect.scoped,\n Effect.tapError((error) =>\n Effect.sync(() => publish({ status: \"error\", error: error.message }))\n ),\n Effect.retry({ schedule: Schedule.spaced(1000), while: (error) => error.retryable }),\n Effect.catch((error) => Effect.logError(\"Connection watch stopped\", error)),\n Effect.forkScoped({ startImmediately: true })\n );\n // Supply a current value while background watch acquisition is pending;\n // the acquisition path repeats this read after registration.\n yield* read(ref.objectType, ref.id).pipe(\n Effect.tap((value) => Effect.sync(() => install(value)))\n );\n const monitor = {\n changes: Stream.callback<ConnectionState>(\n (queue) =>\n Effect.acquireRelease(\n Effect.sync(() => {\n const send = (next: ConnectionState) => {\n Queue.offerUnsafe(queue, next);\n };\n listeners.add(send);\n send(state);\n return send;\n }),\n (send) =>\n Effect.sync(() => {\n listeners.delete(send);\n })\n ),\n { bufferSize: 1, strategy: \"sliding\" }\n ),\n };\n const handlers = options.handlers ?? createDefaultConnectionEgressHandlers();\n const sockets = new Set<WebSocket>();\n const lifetime = new AbortController();\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => {\n listeners.clear();\n lifetime.abort();\n for (const socket of sockets) socket.close();\n sockets.clear();\n })\n );\n const acquired = yield* service.acquire({\n connection: { objectType: ref.objectType, value: row } as SavedConnection,\n serviceInstance,\n credential: currentCredential(),\n handlers: {\n fetch: (request) =>\n handlers.fetch(\n new Request(request, {\n signal: AbortSignal.any([request.signal, lifetime.signal]),\n })\n ),\n createWebSocket: Effect.fnUntraced(function* (\n url: string | URL,\n protocols?: string | string[]\n ) {\n const socket = yield* handlers.createWebSocket(url, protocols);\n if (lifetime.signal.aborted) {\n socket.close();\n return yield* unavailable(\"The selected connection was released.\");\n }\n sockets.add(socket);\n socket.addEventListener(\"close\", () => sockets.delete(socket), { once: true });\n return socket;\n }),\n },\n });\n const scope = yield* Effect.scope;\n const owned = <A>(work: Effect.Effect<A, BackendError>) =>\n Effect.suspend(() =>\n scope.state._tag === \"Closed\"\n ? Effect.fail(unavailable(\"The selected connection was released.\"))\n : Effect.acquireUseRelease(Effect.forkIn(work, scope), Fiber.join, Fiber.interrupt)\n );\n // Compare and persist in one transaction: a late rejection must neither\n // pause a newer login nor resurrect a disconnected row. The ordinary\n // journal/watch path also updates account queries.\n const markNeedsAuthentication = (observed: string | undefined) =>\n options.store\n .transaction(\n Effect.gen(function* () {\n const current = yield* options.store.get(ref.objectType, ref.id);\n if (current?.status === \"active\" && credentialVersion(current) === observed)\n yield* options.store.put(ref.objectType, {\n ...current,\n status: \"needs-auth\",\n });\n })\n )\n .pipe(\n Effect.mapError(connectBackendError),\n Effect.tapError((cause) =>\n Effect.logError(\"Could not save connection authentication status\", cause)\n ),\n Effect.ignore,\n Effect.uninterruptible\n );\n const failed = Effect.fnUntraced(function* (error: BackendError, observed: string | undefined) {\n if (isUnauthenticatedError(error)) yield* markNeedsAuthentication(observed);\n return yield* error;\n });\n // Check an expired external session with its service. Runs only inside `renew`.\n const verifyExternalSession: Effect.Effect<void, BackendError> = Effect.gen(function* () {\n const selected = yield* options.store.get(\"ExternalSessionConnection\", ref.id);\n if (\n !selected ||\n selected.status !== \"active\" ||\n !selected.expiresAt ||\n selected.expiresAt.epochMilliseconds > (yield* Clock.currentTimeMillis)\n )\n return;\n if (!service.externalSession)\n return yield* new BackendError({\n operation: \"connect.session.verify\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"This service cannot verify an external session.\",\n });\n (yield* CredentialObserver)(credentialVersion(selected));\n const verified = yield* Effect.result(\n service.externalSession({\n serviceInstance,\n sessionId: selected.sessionId,\n })\n );\n yield* options.store.transaction(\n Effect.gen(function* () {\n const latest = yield* options.store.get(\"ExternalSessionConnection\", ref.id);\n if (!latest || credentialVersion(latest) !== credentialVersion(selected)) return;\n if (verified._tag === \"Failure\") return yield* verified.failure;\n const identity = verified.success;\n if (\n identity.userId !== selected.userId ||\n (identity.expiresAt &&\n identity.expiresAt.epochMilliseconds <= (yield* Clock.currentTimeMillis))\n )\n return yield* connectError(\n \"NeedsAuthentication\",\n \"The selected external session requires authentication.\"\n );\n yield* options.store.put(\"ExternalSessionConnection\", {\n ...latest,\n title: identity.title ?? latest.title,\n expiresAt: identity.expiresAt,\n });\n })\n );\n }).pipe(\n Effect.mapError((error) =>\n error instanceof BackendError ? error : connectBackendError(error)\n )\n );\n const renewal = yield* Semaphore.make(1);\n // Renew the credential that was saved at `version`, once: concurrent rejections\n // of the same credential share one renewal, and a newer credential wins.\n // Rejections queued behind a renewal that failed share its failure instead of\n // each asking the provider again; a rejection after it tries again.\n let renewals = 0;\n let failedRenewal: { version: number; attempt: number; error: BackendError } | undefined;\n // `expiring` renews ahead of a rejection: an OAuth token about to expire, or an\n // external session whose saved expiry has passed.\n const renew = (version: number, reason: \"rejected\" | \"expiring\" = \"rejected\") =>\n Effect.suspend(() => {\n const waitingSince = renewals;\n return renewal.withPermit(\n Effect.gen(function* () {\n if (version !== credentialGeneration) return;\n if (failedRenewal?.version === version && failedRenewal.attempt > waitingSince)\n return yield* failedRenewal.error;\n const current = yield* read(ref.objectType, ref.id);\n if (current?.status !== \"active\") return;\n if (ref.objectType === \"ExternalSessionConnection\" && reason === \"expiring\") {\n const result = yield* Effect.result(verifyExternalSession);\n install(yield* read(ref.objectType, ref.id));\n // Whether the service rejected the session or could not check it,\n // that is the answer for every request queued on this check.\n if (result._tag === \"Failure\") {\n failedRenewal = { version, attempt: ++renewals, error: result.failure };\n return yield* result.failure;\n }\n renewals++;\n return;\n }\n if (ref.objectType !== \"OAuthConnection\") {\n yield* markNeedsAuthentication(credentialVersion(current));\n return;\n }\n const result = yield* Effect.result(\n backend.applyAction({\n id: crypto.randomUUID(),\n name: \"refreshConnection\",\n parameters: { connectionId: ref.id },\n })\n );\n // Publish now rather than when the row watch catches up, so a\n // concurrent rejection of the old credential does not renew again.\n install(yield* read(ref.objectType, ref.id));\n // A refresh token that no longer works already moved the\n // connection to needs-auth; anything else may succeed later.\n if (result._tag === \"Failure\" && !isUnauthenticatedError(result.failure)) {\n const error = renewalUnavailable(result.failure);\n failedRenewal = { version, attempt: ++renewals, error };\n return yield* error;\n }\n renewals++;\n })\n );\n });\n const requireAuthentication = Effect.fnUntraced(function* () {\n const current = yield* read(ref.objectType, ref.id);\n if (!current || current.status === \"inactive\")\n return yield* unavailable(\"The selected connection is disconnected.\");\n if (current.status !== \"active\")\n return yield* unavailable(\"The selected connection requires authentication.\");\n return current;\n });\n const egress: ConnectionEgress = {\n fetch: (input, init) =>\n owned(\n Effect.gen(function* () {\n const version = credentialGeneration;\n let observed = credentialVersion(yield* requireAuthentication());\n const request = yield* Effect.try({\n try: () => new Request(input, init),\n catch: (cause) => classifyBackendFailure(\"connect.egress.fetch\", cause),\n });\n // Only a request without a body is sent again after a renewal. A body\n // can be a one-shot stream (a proxied upload); the outbox or sync\n // retries those after the renewal instead.\n const replay = request.body === null ? request.clone() : undefined;\n const send = (value: Request) =>\n acquired.fetch(value).pipe(\n Effect.provideService(CredentialObserver, (value) => {\n observed = value;\n })\n );\n const first = yield* Effect.result(send(request));\n if (first._tag === \"Success\") return first.success;\n if (\n !isUnauthenticatedError(first.failure) ||\n ref.objectType !== \"OAuthConnection\"\n )\n return yield* failed(first.failure, observed);\n yield* renew(version);\n if (state.status !== \"active\") return yield* first.failure;\n if (!replay) return yield* retryAfterRenewal();\n observed = credentialVersion(yield* requireAuthentication());\n return yield* send(replay).pipe(Effect.catch((error) => failed(error, observed)));\n })\n ),\n createWebSocket: (url, protocols) =>\n owned(\n Effect.gen(function* () {\n let observed = credentialVersion(yield* requireAuthentication());\n return yield* acquired.createWebSocket(url, protocols).pipe(\n Effect.provideService(CredentialObserver, (value) => {\n observed = value;\n }),\n Effect.catch((error) => failed(error, observed))\n );\n })\n ),\n };\n const authentication: ConnectionLifecycle = {\n get state() {\n return state;\n },\n changes: monitor.changes,\n get credentialVersion() {\n return credentialGeneration;\n },\n refresh: renew,\n };\n return {\n connection: ref,\n userId: row.userId,\n serviceInstance: serviceInstance as ServiceInstanceRecord,\n egress,\n authentication,\n } satisfies ConnectionAccess;\n }),\n });\n return {\n acquire: (connection: ConnectionRef) => RcMap.get(access, Schema.encodeSync(codec)(connection)),\n };\n});\n"],"mappings":";;;;;;;;;AA+BA,MAAM,eAAe,YACjB,IAAI,aAAa;CACb,WAAW;CACX,MAAM;CACN,WAAW;CACX;AACJ,CAAC;AAIL,MAAM,qBAAqB,QAAQ,UAC/B,2CACA,EAAE,0BA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|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"files": [
|
|
5
5
|
"lib"
|
|
6
6
|
],
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"effect": "^4.0.5",
|
|
24
24
|
"oauth4webapi": "^3.8.7",
|
|
25
25
|
"temporal-polyfill": "^0.3.0",
|
|
26
|
-
"@party-stack/ontology-backend": "0.
|
|
26
|
+
"@party-stack/ontology-backend": "0.4.0",
|
|
27
27
|
"@party-stack/ontology-spec": "0.4.0",
|
|
28
28
|
"@party-stack/ontology-storage": "0.3.1",
|
|
29
29
|
"@party-stack/runtime": "0.6.2"
|