@party-stack/connect 0.2.1 → 0.3.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/README.md CHANGED
@@ -24,9 +24,21 @@ encryption keys; a persistent browser runtime must opt into persistent key stora
24
24
  `ConnectManager.layer(options)` provides the same service through an Effect Layer.
25
25
 
26
26
  ```ts
27
- const connect =
28
- yield *
29
- makeConnectManager({
27
+ import { makeConnectManager } from "@party-stack/connect";
28
+ import { makeFoundryBackend, makeFoundryServiceConnector } from "@party-stack/foundry-ontology";
29
+ import { Effect } from "effect";
30
+ import type { OntologyIR } from "@party-stack/ontology-spec";
31
+
32
+ // Requires Runtime and Scope.
33
+ export const openFoundryBackend = Effect.fn("App.openFoundryBackend")(function* (options: {
34
+ readonly clientId: string;
35
+ readonly redirectUrl: string;
36
+ readonly connectionId: string;
37
+ readonly ontologyId: string;
38
+ readonly ir: OntologyIR;
39
+ }) {
40
+ const { clientId, redirectUrl, connectionId, ontologyId, ir } = options;
41
+ const connect = yield* makeConnectManager({
30
42
  services: [
31
43
  {
32
44
  connector: makeFoundryServiceConnector(),
@@ -47,17 +59,15 @@ const connect =
47
59
  },
48
60
  ],
49
61
  });
50
-
51
- const access = yield * connect.connections.acquire({ objectType: "OAuthConnection", id: connectionId });
52
- const backend =
53
- yield *
54
- makeFoundryBackend({
62
+ const access = yield* connect.connections.acquire({ objectType: "OAuthConnection", id: connectionId });
63
+ return yield* makeFoundryBackend({
55
64
  baseUrl: access.serviceInstance.instanceUrl,
56
65
  ontologyId,
57
66
  ir,
58
67
  context: { userId: access.userId },
59
68
  egress: access.egress,
60
69
  });
70
+ });
61
71
  ```
62
72
 
63
73
  The manager holds scoped authenticated I/O, watches credential changes and
@@ -65,6 +75,18 @@ releases sockets/requests when their owner closes. Each outgoing request uses th
65
75
  current credential. A response using old credentials cannot pause a newer login.
66
76
  It does not persist a second connection inventory.
67
77
 
78
+ OAuth access tokens are renewed a minute before they expire. When a service still
79
+ rejects one (a connector reports it as `Unauthenticated`, for example through
80
+ `withHttpAuthenticationErrors`), Connect renews it once, however many requests were
81
+ rejected, and sends a request without a body again. A request with a body fails with
82
+ a retryable error after the renewal, for the outbox or sync to retry. If the
83
+ credential cannot be renewed, the connection moves to `needs-auth`. Connectors never
84
+ refresh credentials themselves.
85
+
86
+ Pass `access.authentication` to the replica that syncs the connection. Besides the
87
+ connection state, it can renew a credential that a source rejects after egress has
88
+ returned, such as a websocket closed when its token expires.
89
+
68
90
  Only an instance URL and each OAuth application's client configuration are required.
69
91
  Instance IDs default to a stable service + canonical URL key; application IDs default
70
92
  to instance ID + client ID. Titles default to the connector's display name, and flow
@@ -150,12 +172,17 @@ so `server.forget(name)` works after credentials expire.
150
172
  For a private SharedWorker, `connectDeviceRoute(manager)` returns its route binding:
151
173
 
152
174
  ```ts
153
- const server =
154
- yield *
155
- makeOntologyServer({
175
+ import { ConnectManager, connectDeviceRoute } from "@party-stack/connect";
176
+ import { makeOntologyServer } from "@party-stack/ontology-server";
177
+ import { Effect } from "effect";
178
+
179
+ export const openDeviceServer = Effect.gen(function* () {
180
+ const manager = yield* ConnectManager;
181
+ return yield* makeOntologyServer({
156
182
  enableRealtime: true,
157
183
  routes: { connect: connectDeviceRoute(manager) },
158
184
  });
185
+ });
159
186
  ```
160
187
 
161
188
  This convenience uses `connectPublicOntologyIR`, the device-local inventory policy.
@@ -55,12 +55,11 @@ export interface ServiceConnector {
55
55
  readonly acquire: (input: {
56
56
  readonly connection: SavedConnection;
57
57
  readonly serviceInstance: ServiceInstanceRecord;
58
- /** Rechecks and decrypts the saved credential; OAuth refresh is coordinated by Connect. */
58
+ /** Rechecks and decrypts the saved credential. Read it for every request: Connect
59
+ * renews it before it expires and after the service rejects it. Report a rejection
60
+ * as an `Unauthenticated` error (see withHttpAuthenticationErrors); Connect renews
61
+ * the credential and retries or fails the request as appropriate. */
59
62
  readonly credential: Effect.Effect<string, BackendError>;
60
- /** Refresh a rejected OAuth credential only if it is still current. An
61
- * older response must not replace a newer login or another refresh.
62
- */
63
- readonly refreshCredential: (rejected: string) => Effect.Effect<string, BackendError>;
64
63
  readonly handlers: ConnectionEgressHandlers;
65
64
  }) => Effect.Effect<ConnectionEgressHandlers, BackendError, Scope.Scope>;
66
65
  }
@@ -1 +1 @@
1
- {"version":3,"file":"ServiceConnector.d.ts","names":[],"sources":["../src/ServiceConnector.ts"],"mappings":";;;;;;;;;;;YAiBY;WACK;WAAwC,OAAO;;WAC/C;WAAyC,OAAO;;WAChD;WAAkD,OAAO;;YAC9D;WAA2B,YAAY;WAAwC;;iBAE1E;WACJ;WACA;WACA,YAAY,SAAS;;;;;iBAMjB;WACJ;WACA;WACA;WACA,SAAS;aACL,aAAa;aACb,iBAAiB;aACjB,QAAQ;QACf,OAAO,OAAO,qBAAqB;WAChC,UAAU;aACN,iBAAiB;aACjB;QACP,OAAO,OAAO,yBAAyB;WACpC,mBAAmB;aACf,iBAAiB;aACjB;QACP,OAAO,OAAO,yBAAyB;WACpC,6BAA6B;aACzB,iBAAiB;aACjB;QACP,OAAO,aAAa;WACjB,UAAU;aACN,YAAY;aACZ,iBAAiB;;aAEjB,YAAY,OAAO,eAAe;;;;aAIlC,oBAAoB,qBAAqB,OAAO,eAAe;aAC/D,UAAU;QACjB,OAAO,OAAO,0BAA0B,cAAc,MAAM"}
1
+ {"version":3,"file":"ServiceConnector.d.ts","names":[],"sources":["../src/ServiceConnector.ts"],"mappings":";;;;;;;;;;;YAiBY;WACK;WAAwC,OAAO;;WAC/C;WAAyC,OAAO;;WAChD;WAAkD,OAAO;;YAC9D;WAA2B,YAAY;WAAwC;;iBAE1E;WACJ;WACA;WACA,YAAY,SAAS;;;;;iBAMjB;WACJ;WACA;WACA;WACA,SAAS;aACL,aAAa;aACb,iBAAiB;aACjB,QAAQ;QACf,OAAO,OAAO,qBAAqB;WAChC,UAAU;aACN,iBAAiB;aACjB;QACP,OAAO,OAAO,yBAAyB;WACpC,mBAAmB;aACf,iBAAiB;aACjB;QACP,OAAO,OAAO,yBAAyB;WACpC,6BAA6B;aACzB,iBAAiB;aACjB;QACP,OAAO,aAAa;WACjB,UAAU;aACN,YAAY;aACZ,iBAAiB;;;;;aAKjB,YAAY,OAAO,eAAe;aAClC,UAAU;QACjB,OAAO,OAAO,0BAA0B,cAAc,MAAM"}
@@ -1,5 +1,5 @@
1
1
  import { ServiceInstanceRecord } from "./spec/index.js";
2
- import { ConnectionEgress, ConnectionMonitor } from "./types.js";
2
+ import { ConnectionEgress, ConnectionLifecycle } from "./types.js";
3
3
  import { ConnectManagerService } from "./makeConnectManager.js";
4
4
  import { BackendError } from "@party-stack/ontology-backend";
5
5
  import { Effect } from "effect";
@@ -26,7 +26,7 @@ export declare const acquireConfiguredConnection: (options: {
26
26
  userId: string;
27
27
  serviceInstance: ServiceInstanceRecord;
28
28
  egress: ConnectionEgress;
29
- authentication: ConnectionMonitor;
29
+ authentication: ConnectionLifecycle;
30
30
  }, BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, import("effect/Scope").Scope>;
31
31
  //#endregion
32
32
  //# sourceMappingURL=acquireConfiguredConnection.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"acquireConfiguredConnection.d.ts","names":["_$__spec_index_js0.ServiceInstanceRecord","_$__types_js0.ConnectionEgress","_$__types_js0.ConnectionMonitor"],"sources":["../src/acquireConfiguredConnection.ts"],"mappings":";;;;;;;;;;qBAYa,8BAA2B;WAEd,SAAA;WACU;WACX;aAAW;aAAgC;;WAC1C;WACA;WACe,wBAAA;;;;;;;mBAAAA;;;GAoDxC,wXAAA"}
1
+ {"version":3,"file":"acquireConfiguredConnection.d.ts","names":["_$__spec_index_js0.ServiceInstanceRecord","_$__types_js0.ConnectionEgress","_$__types_js0.ConnectionLifecycle"],"sources":["../src/acquireConfiguredConnection.ts"],"mappings":";;;;;;;;;;qBAYa,8BAA2B;WAEd,SAAA;WACU;WACX;aAAW;aAAgC;;WAC1C;WACA;WACe,wBAAA;;;;;;;mBAAAA;;;GAoDxC,wXAAA"}
@@ -165,7 +165,8 @@ function makeOAuthAuthorizationClient(options) {
165
165
  operation: "authorization.presentation",
166
166
  kind: "Unavailable",
167
167
  retryable: false,
168
- message: cause.message
168
+ message: cause.message,
169
+ cause
169
170
  })))
170
171
  };
171
172
  }
@@ -1 +1 @@
1
- {"version":3,"file":"authorization.js","names":[],"sources":["../src/authorization.ts"],"sourcesContent":["import { BackendError } from \"@party-stack/ontology-backend\";\nimport { o, type OntologyIR } from \"@party-stack/ontology-spec\";\nimport * as q from \"@party-stack/ontology-spec/query\";\nimport { Effect, Schema } from \"effect\";\nimport { connectOntology } from \"./spec/index.js\";\nimport type { Connection } from \"./types.js\";\nimport type { OntologyBackendService } from \"@party-stack/ontology-backend\";\nimport type { BrowserAuthentication, BrowserAuthenticationPresentation } from \"@party-stack/runtime\";\n\n/** A credential owner's native backend plus its fixed authorization binding.\n * Transports project this policy before exposing the backend to a caller.\n */\nexport interface OAuthAuthorizationSource {\n readonly backend: OntologyBackendService;\n readonly ir: OntologyIR;\n readonly context: {\n readonly applicationId: string;\n readonly principalId: string;\n readonly redirectUrl: string;\n };\n}\n\nexport interface OAuthAuthorizationClient {\n readonly redirectUrl: string;\n readonly signIn: (options?: {\n browserPresentation?: BrowserAuthenticationPresentation;\n connectionId?: string;\n }) => Effect.Effect<Connection<\"active\"> & { readonly id: string }, BackendError>;\n readonly complete: (\n callbackUrl: string\n ) => Effect.Effect<(Connection<\"active\"> & { readonly id: string }) | undefined, BackendError>;\n}\n\n/** Only connection identity/status is readable. Credentials and PKCE attempts stay private. */\nexport const oauthAuthorizationOntology: OntologyIR = {\n ...connectOntology,\n context: {\n type: o.struct({\n fields: [\n { name: \"applicationId\", displayName: \"Connector\", type: o.string({}) },\n { name: \"principalId\", displayName: \"Principal\", type: o.string({}) },\n { name: \"redirectUrl\", displayName: \"Redirect URL\", type: o.string({}) },\n ],\n }),\n },\n policy: {\n objects: {\n select: [\n q.sub(\"connections\", {\n from: { source: { objectType: \"OAuthConnection\" }, binding: \"c\" },\n where: q.eq(q.field(\"c\", \"application\"), q.context(\"applicationId\")),\n select: [\"id\", \"userId\", \"status\"].map((name) => q.selectField(name, q.field(\"c\", name))),\n }),\n ],\n },\n actions: [\n {\n actionType: \"beginAuthorization\",\n check: q.literal(true),\n bind: [\"applicationId\", \"principalId\", \"redirectUrl\"].map((parameter) => ({\n parameter,\n expression: q.context(parameter),\n })),\n additionalObjects: {\n select: [\n q.sub(\"application\", {\n from: { source: { objectType: \"OAuthApplication\" }, binding: \"application\" },\n where: q.eq(q.field(\"application\", \"id\"), q.context(\"applicationId\")),\n select: [q.selectField(\"id\", q.field(\"application\", \"id\"))],\n }),\n ],\n },\n },\n {\n actionType: \"completeAuthorization\",\n check: q.literal(true),\n bind: [{ parameter: \"principalId\", expression: q.context(\"principalId\") }],\n },\n ],\n },\n};\n\n/** Trusted in-process counterpart of the server's IR policy binding. */\nexport function bindOAuthAuthorizationBackend(source: OAuthAuthorizationSource): OntologyBackendService {\n return {\n ...source.backend,\n applyAction: (request) => {\n const parameters =\n request.name === \"beginAuthorization\"\n ? { ...request.parameters, ...source.context }\n : request.name === \"completeAuthorization\"\n ? { ...request.parameters, principalId: source.context.principalId }\n : undefined;\n return parameters\n ? source.backend.applyAction({ ...request, parameters })\n : Effect.fail(\n new BackendError({\n operation: \"authorization\",\n kind: \"NotImplemented\",\n retryable: false,\n message: \"Unknown authorization action.\",\n })\n );\n },\n };\n}\n\nconst Started = Schema.Struct({ id: Schema.String, authorizationUrl: Schema.String });\nconst Completed = Schema.Struct({ connectionId: Schema.String });\nconst Account = Schema.Struct({ userId: Schema.String, status: Schema.Literal(\"active\") });\nconst invalid = () =>\n new BackendError({\n operation: \"authorization\",\n kind: \"InvalidResponse\",\n retryable: false,\n message: \"Authorization returned an invalid response.\",\n });\n\n/** Browser orchestration over ordinary Connect actions; no dedicated OAuth RPCs. */\nexport function makeOAuthAuthorizationClient(options: {\n backend: OntologyBackendService;\n applicationId?: string;\n redirectUrl: string;\n browserAuthentication?: BrowserAuthentication;\n}): OAuthAuthorizationClient {\n const apply = (name: string, parameters: Record<string, unknown>) =>\n options.backend.applyAction({ id: crypto.randomUUID(), name, parameters });\n const complete = Effect.fn(\"Connect.authorization.complete\")(function* (callbackUrl: string) {\n const url = yield* Effect.try({ try: () => new URL(callbackUrl), catch: invalid });\n if (!url.searchParams.has(\"state\")) return;\n const receipt = yield* apply(\"completeAuthorization\", { callbackUrl });\n const { connectionId } = yield* Schema.decodeUnknownEffect(Completed)(receipt.result).pipe(\n Effect.mapError(invalid)\n );\n const rows = yield* options.backend.query({\n select: [\n q.sub(\"connection\", {\n from: { source: { objectType: \"OAuthConnection\" }, binding: \"c\" },\n where: q.eq(q.field(\"c\", \"id\"), q.literal(connectionId)),\n page: { limit: 1 },\n select: [\n q.selectField(\"userId\", q.field(\"c\", \"userId\")),\n q.selectField(\"status\", q.field(\"c\", \"status\")),\n ],\n }),\n ],\n });\n const [account] = yield* Schema.decodeUnknownEffect(Schema.Array(Account))(rows.connection).pipe(\n Effect.mapError(invalid)\n );\n if (!account) return yield* invalid();\n return { id: connectionId, userId: account.userId, state: { status: \"active\" as const } };\n });\n return {\n redirectUrl: options.redirectUrl,\n complete,\n signIn: Effect.fn(\"Connect.authorization.signIn\")(\n function* (settings) {\n const browser = options.browserAuthentication;\n if (!browser)\n return yield* new BackendError({\n operation: \"authorization\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"Interactive authorization requires a browser authentication capability.\",\n });\n const presentation = yield* browser.start({\n redirectUrl: options.redirectUrl,\n presentation: settings?.browserPresentation,\n });\n const receipt = yield* apply(\"beginAuthorization\", {\n applicationId: options.applicationId,\n redirectUrl: options.redirectUrl,\n connectionId: settings?.connectionId,\n });\n const started = yield* Schema.decodeUnknownEffect(Started)(receipt.result).pipe(\n Effect.mapError(invalid)\n );\n const { callbackUrl } = yield* presentation.open(started.authorizationUrl);\n const connection = yield* complete(callbackUrl);\n if (!connection) return yield* invalid();\n return connection;\n },\n Effect.scoped,\n Effect.mapError((cause) =>\n cause instanceof BackendError\n ? cause\n : new BackendError({\n operation: \"authorization.presentation\",\n kind: \"Unavailable\",\n retryable: false,\n message: cause.message,\n })\n )\n ),\n };\n}\n"],"mappings":";;;;;;;AAkCA,MAAa,6BAAyC;CAClD,GAAG;CACH,SAAS,EACL,MAAM,EAAE,OAAO,EACX,QAAQ;EACJ;GAAE,MAAM;GAAiB,aAAa;GAAa,MAAM,EAAE,OAAO,CAAC,CAAC;EAAE;EACtE;GAAE,MAAM;GAAe,aAAa;GAAa,MAAM,EAAE,OAAO,CAAC,CAAC;EAAE;EACpE;GAAE,MAAM;GAAe,aAAa;GAAgB,MAAM,EAAE,OAAO,CAAC,CAAC;EAAE;CAC3E,EACJ,CAAC,EACL;CACA,QAAQ;EACJ,SAAS,EACL,QAAQ,CACJ,EAAE,IAAI,eAAe;GACjB,MAAM;IAAE,QAAQ,EAAE,YAAY,kBAAkB;IAAG,SAAS;GAAI;GAChE,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,aAAa,GAAG,EAAE,QAAQ,eAAe,CAAC;GACnE,QAAQ;IAAC;IAAM;IAAU;GAAQ,CAAC,CAAC,KAAK,SAAS,EAAE,YAAY,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC,CAAC;EAC5F,CAAC,CACL,EACJ;EACA,SAAS,CACL;GACI,YAAY;GACZ,OAAO,EAAE,QAAQ,IAAI;GACrB,MAAM;IAAC;IAAiB;IAAe;GAAa,CAAC,CAAC,KAAK,eAAe;IACtE;IACA,YAAY,EAAE,QAAQ,SAAS;GACnC,EAAE;GACF,mBAAmB,EACf,QAAQ,CACJ,EAAE,IAAI,eAAe;IACjB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AAO,IAAI,aAAa;IAC3B,WAAW;IACX,MAAM;IACN,WAAW;IACX,SAAS;GACb,CAAC;GACL,MAAM,eAAe,OAAO,QAAQ,MAAM;IACtC,aAAa,QAAQ;IACrB,cAAc,UAAU;GAC5B,CAAC;GACD,MAAM,UAAU,OAAO,MAAM,sBAAsB;IAC/C,eAAe,QAAQ;IACvB,aAAa,QAAQ;IACrB,cAAc,UAAU;GAC5B,CAAC;GACD,MAAM,UAAU,OAAO,OAAO,oBAAoB,OAAO,CAAC,CAAC,QAAQ,MAAM,CAAC,CAAC,KACvE,OAAO,SAAS,OAAO,CAC3B;GACA,MAAM,EAAE,gBAAgB,OAAO,aAAa,KAAK,QAAQ,gBAAgB;GACzE,MAAM,aAAa,OAAO,SAAS,WAAW;GAC9C,IAAI,CAAC,YAAY,OAAO,OAAO,QAAQ;GACvC,OAAO;EACX,GACA,OAAO,QACP,OAAO,UAAU,UACb,iBAAiB,eACX,QACA,IAAI,aAAa;GACb,WAAW;GACX,MAAM;GACN,WAAW;GACX,SAAS,MAAM;EACnB,CAAC,CACX,CACJ;CACJ;AACJ"}
1
+ {"version":3,"file":"authorization.js","names":[],"sources":["../src/authorization.ts"],"sourcesContent":["import { BackendError } from \"@party-stack/ontology-backend\";\nimport { o, type OntologyIR } from \"@party-stack/ontology-spec\";\nimport * as q from \"@party-stack/ontology-spec/query\";\nimport { Effect, Schema } from \"effect\";\nimport { connectOntology } from \"./spec/index.js\";\nimport type { Connection } from \"./types.js\";\nimport type { OntologyBackendService } from \"@party-stack/ontology-backend\";\nimport type { BrowserAuthentication, BrowserAuthenticationPresentation } from \"@party-stack/runtime\";\n\n/** A credential owner's native backend plus its fixed authorization binding.\n * Transports project this policy before exposing the backend to a caller.\n */\nexport interface OAuthAuthorizationSource {\n readonly backend: OntologyBackendService;\n readonly ir: OntologyIR;\n readonly context: {\n readonly applicationId: string;\n readonly principalId: string;\n readonly redirectUrl: string;\n };\n}\n\nexport interface OAuthAuthorizationClient {\n readonly redirectUrl: string;\n readonly signIn: (options?: {\n browserPresentation?: BrowserAuthenticationPresentation;\n connectionId?: string;\n }) => Effect.Effect<Connection<\"active\"> & { readonly id: string }, BackendError>;\n readonly complete: (\n callbackUrl: string\n ) => Effect.Effect<(Connection<\"active\"> & { readonly id: string }) | undefined, BackendError>;\n}\n\n/** Only connection identity/status is readable. Credentials and PKCE attempts stay private. */\nexport const oauthAuthorizationOntology: OntologyIR = {\n ...connectOntology,\n context: {\n type: o.struct({\n fields: [\n { name: \"applicationId\", displayName: \"Connector\", type: o.string({}) },\n { name: \"principalId\", displayName: \"Principal\", type: o.string({}) },\n { name: \"redirectUrl\", displayName: \"Redirect URL\", type: o.string({}) },\n ],\n }),\n },\n policy: {\n objects: {\n select: [\n q.sub(\"connections\", {\n from: { source: { objectType: \"OAuthConnection\" }, binding: \"c\" },\n where: q.eq(q.field(\"c\", \"application\"), q.context(\"applicationId\")),\n select: [\"id\", \"userId\", \"status\"].map((name) => q.selectField(name, q.field(\"c\", name))),\n }),\n ],\n },\n actions: [\n {\n actionType: \"beginAuthorization\",\n check: q.literal(true),\n bind: [\"applicationId\", \"principalId\", \"redirectUrl\"].map((parameter) => ({\n parameter,\n expression: q.context(parameter),\n })),\n additionalObjects: {\n select: [\n q.sub(\"application\", {\n from: { source: { objectType: \"OAuthApplication\" }, binding: \"application\" },\n where: q.eq(q.field(\"application\", \"id\"), q.context(\"applicationId\")),\n select: [q.selectField(\"id\", q.field(\"application\", \"id\"))],\n }),\n ],\n },\n },\n {\n actionType: \"completeAuthorization\",\n check: q.literal(true),\n bind: [{ parameter: \"principalId\", expression: q.context(\"principalId\") }],\n },\n ],\n },\n};\n\n/** Trusted in-process counterpart of the server's IR policy binding. */\nexport function bindOAuthAuthorizationBackend(source: OAuthAuthorizationSource): OntologyBackendService {\n return {\n ...source.backend,\n applyAction: (request) => {\n const parameters =\n request.name === \"beginAuthorization\"\n ? { ...request.parameters, ...source.context }\n : request.name === \"completeAuthorization\"\n ? { ...request.parameters, principalId: source.context.principalId }\n : undefined;\n return parameters\n ? source.backend.applyAction({ ...request, parameters })\n : Effect.fail(\n new BackendError({\n operation: \"authorization\",\n kind: \"NotImplemented\",\n retryable: false,\n message: \"Unknown authorization action.\",\n })\n );\n },\n };\n}\n\nconst Started = Schema.Struct({ id: Schema.String, authorizationUrl: Schema.String });\nconst Completed = Schema.Struct({ connectionId: Schema.String });\nconst Account = Schema.Struct({ userId: Schema.String, status: Schema.Literal(\"active\") });\nconst invalid = () =>\n new BackendError({\n operation: \"authorization\",\n kind: \"InvalidResponse\",\n retryable: false,\n message: \"Authorization returned an invalid response.\",\n });\n\n/** Browser orchestration over ordinary Connect actions; no dedicated OAuth RPCs. */\nexport function makeOAuthAuthorizationClient(options: {\n backend: OntologyBackendService;\n applicationId?: string;\n redirectUrl: string;\n browserAuthentication?: BrowserAuthentication;\n}): OAuthAuthorizationClient {\n const apply = (name: string, parameters: Record<string, unknown>) =>\n options.backend.applyAction({ id: crypto.randomUUID(), name, parameters });\n const complete = Effect.fn(\"Connect.authorization.complete\")(function* (callbackUrl: string) {\n const url = yield* Effect.try({ try: () => new URL(callbackUrl), catch: invalid });\n if (!url.searchParams.has(\"state\")) return;\n const receipt = yield* apply(\"completeAuthorization\", { callbackUrl });\n const { connectionId } = yield* Schema.decodeUnknownEffect(Completed)(receipt.result).pipe(\n Effect.mapError(invalid)\n );\n const rows = yield* options.backend.query({\n select: [\n q.sub(\"connection\", {\n from: { source: { objectType: \"OAuthConnection\" }, binding: \"c\" },\n where: q.eq(q.field(\"c\", \"id\"), q.literal(connectionId)),\n page: { limit: 1 },\n select: [\n q.selectField(\"userId\", q.field(\"c\", \"userId\")),\n q.selectField(\"status\", q.field(\"c\", \"status\")),\n ],\n }),\n ],\n });\n const [account] = yield* Schema.decodeUnknownEffect(Schema.Array(Account))(rows.connection).pipe(\n Effect.mapError(invalid)\n );\n if (!account) return yield* invalid();\n return { id: connectionId, userId: account.userId, state: { status: \"active\" as const } };\n });\n return {\n redirectUrl: options.redirectUrl,\n complete,\n signIn: Effect.fn(\"Connect.authorization.signIn\")(\n function* (settings) {\n const browser = options.browserAuthentication;\n if (!browser)\n return yield* new BackendError({\n operation: \"authorization\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"Interactive authorization requires a browser authentication capability.\",\n });\n const presentation = yield* browser.start({\n redirectUrl: options.redirectUrl,\n presentation: settings?.browserPresentation,\n });\n const receipt = yield* apply(\"beginAuthorization\", {\n applicationId: options.applicationId,\n redirectUrl: options.redirectUrl,\n connectionId: settings?.connectionId,\n });\n const started = yield* Schema.decodeUnknownEffect(Started)(receipt.result).pipe(\n Effect.mapError(invalid)\n );\n const { callbackUrl } = yield* presentation.open(started.authorizationUrl);\n const connection = yield* complete(callbackUrl);\n if (!connection) return yield* invalid();\n return connection;\n },\n Effect.scoped,\n Effect.mapError((cause) =>\n cause instanceof BackendError\n ? cause\n : new BackendError({\n operation: \"authorization.presentation\",\n kind: \"Unavailable\",\n retryable: false,\n message: cause.message,\n // Keeps the browser's reason, e.g. PopupBlocked, for a redirect fallback.\n cause,\n })\n )\n ),\n };\n}\n"],"mappings":";;;;;;;AAkCA,MAAa,6BAAyC;CAClD,GAAG;CACH,SAAS,EACL,MAAM,EAAE,OAAO,EACX,QAAQ;EACJ;GAAE,MAAM;GAAiB,aAAa;GAAa,MAAM,EAAE,OAAO,CAAC,CAAC;EAAE;EACtE;GAAE,MAAM;GAAe,aAAa;GAAa,MAAM,EAAE,OAAO,CAAC,CAAC;EAAE;EACpE;GAAE,MAAM;GAAe,aAAa;GAAgB,MAAM,EAAE,OAAO,CAAC,CAAC;EAAE;CAC3E,EACJ,CAAC,EACL;CACA,QAAQ;EACJ,SAAS,EACL,QAAQ,CACJ,EAAE,IAAI,eAAe;GACjB,MAAM;IAAE,QAAQ,EAAE,YAAY,kBAAkB;IAAG,SAAS;GAAI;GAChE,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,aAAa,GAAG,EAAE,QAAQ,eAAe,CAAC;G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CAAC,CAAC,CAAC,KAAK,UAAU,CAAC,CAAC,KACxF,OAAO,SAAS,OAAO,CAC3B;EACA,IAAI,CAAC,SAAS,OAAO,OAAO,QAAQ;EACpC,OAAO;GAAE,IAAI;GAAc,QAAQ,QAAQ;GAAQ,OAAO,EAAE,QAAQ,SAAkB;EAAE;CAC5F,CAAC;CACD,OAAO;EACH,aAAa,QAAQ;EACrB;EACA,QAAQ,OAAO,GAAG,8BAA8B,CAAC,CAC7C,WAAW,UAAU;GACjB,MAAM,UAAU,QAAQ;GACxB,IAAI,CAAC,SACD,OAAO,OAAO,IAAI,aAAa;IAC3B,WAAW;IACX,MAAM;IACN,WAAW;IACX,SAAS;GACb,CAAC;GACL,MAAM,eAAe,OAAO,QAAQ,MAAM;IACtC,aAAa,QAAQ;IACrB,cAAc,UAAU;GAC5B,CAAC;GACD,MAAM,UAAU,OAAO,MAAM,sBAAsB;IAC/C,eAAe,QAAQ;IACvB,aAAa,QAAQ;IACrB,cAAc,UAAU;GAC5B,CAAC;GACD,MAAM,UAAU,OAAO,OAAO,oBAAoB,OAAO,CAAC,CAAC,QAAQ,MAAM,CAAC,CAAC,KACvE,OAAO,SAAS,OAAO,CAC3B;GACA,MAAM,EAAE,gBAAgB,OAAO,aAAa,KAAK,QAAQ,gBAAgB;GACzE,MAAM,aAAa,OAAO,SAAS,WAAW;GAC9C,IAAI,CAAC,YAAY,OAAO,OAAO,QAAQ;GACvC,OAAO;EACX,GACA,OAAO,QACP,OAAO,UAAU,UACb,iBAAiB,eACX,QACA,IAAI,aAAa;GACb,WAAW;GACX,MAAM;GACN,WAAW;GACX,SAAS,MAAM;GAEf;EACJ,CAAC,CACX,CACJ;CACJ;AACJ"}
@@ -1,6 +1,8 @@
1
1
  import { BackendError, OntologyBackendService } from "@party-stack/ontology-backend";
2
2
  import { Effect } from "effect";
3
3
  //#region src/core/accessToken.d.ts
4
+ /** Renew an access token this long before it expires. */
5
+ export declare const accessTokenRenewalWindowMs = 60000;
4
6
  /** Egress convenience over ordinary reads, refresh action and property decryption.
5
7
  * The supplied backend may be local or remote and must authorize token-property
6
8
  * access. This adds no alternate permission path or credential-returning RPC.
@@ -1 +1 @@
1
- {"version":3,"file":"accessToken.d.ts","names":[],"sources":["../../src/core/accessToken.ts"],"mappings":";;;;;;;qBAgBa,wBAAqB,SAAA,wBAAA,yBAAA,OAAA,eAAA"}
1
+ {"version":3,"file":"accessToken.d.ts","names":[],"sources":["../../src/core/accessToken.ts"],"mappings":";;;;qBAOa;;;;;qBAWA,wBAAqB,SAAA,wBAAA,yBAAA,OAAA,eAAA"}
@@ -3,6 +3,8 @@ import { Clock, Effect, Schema } from "effect";
3
3
  import * as q from "@party-stack/ontology-spec/query";
4
4
  import { TemporalTimestamp } from "@party-stack/ontology-spec/effect";
5
5
  //#region src/core/accessToken.ts
6
+ /** Renew an access token this long before it expires. */
7
+ const accessTokenRenewalWindowMs = 6e4;
6
8
  const State = Schema.Struct({
7
9
  status: Schema.Literals([
8
10
  "active",
@@ -52,7 +54,7 @@ const connectionAccessToken = Effect.fn("Connect.accessToken")(function* (backen
52
54
  });
53
55
  let current = yield* read();
54
56
  const now = yield* Clock.currentTimeMillis;
55
- if (!current.accessToken || current.status === "inactive" || current.accessTokenExpiresAt && current.accessTokenExpiresAt.epochMilliseconds <= now + 5e3) {
57
+ if (!current.accessToken || current.status === "inactive" || current.accessTokenExpiresAt && current.accessTokenExpiresAt.epochMilliseconds <= now + 6e4) {
56
58
  yield* backend.applyAction({
57
59
  id: crypto.randomUUID(),
58
60
  name: "refreshConnection",
@@ -82,6 +84,6 @@ const connectionAccessToken = Effect.fn("Connect.accessToken")(function* (backen
82
84
  })));
83
85
  });
84
86
  //#endregion
85
- export { connectionAccessToken };
87
+ export { accessTokenRenewalWindowMs, connectionAccessToken };
86
88
 
87
89
  //# 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\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 const now = yield* Clock.currentTimeMillis;\n // An expired refresh token does not invalidate an otherwise usable access token.\n if (\n !current.accessToken ||\n current.status === \"inactive\" ||\n (current.accessTokenExpiresAt && current.accessTokenExpiresAt.epochMilliseconds <= now + 5_000)\n ) {\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":";;;;;AAMA,MAAM,QAAQ,OAAO,OAAO;CACxB,QAAQ,OAAO,SAAS;EAAC;EAAU;EAAc;CAAU,CAAC;CAC5D,aAAa,OAAO,SAAS,oBAAoB;CACjD,sBAAsB,OAAO,SAAS,iBAAiB;AAC3D,CAAC;;;;;AAMD,MAAa,wBAAwB,OAAO,GAAG,qBAAqB,CAAC,CAAC,WAClE,SACA,cACF;CACE,IAAI,CAAC,QAAQ,WACT,OAAO,OAAO,IAAI,aAAa;EAC3B,WAAW;EACX,MAAM;EACN,WAAW;EACX,SAAS;CACb,CAAC;CACL,MAAM,OAAO,OAAO,WAAW,aAAa;EACxC,MAAM,SAAS,OAAO,QAAQ,MAAM,EAChC,QAAQ,CACJ,EAAE,IAAI,eAAe;GACjB,MAAM;IAAE,QAAQ,EAAE,YAAY,kBAAkB;IAAG,SAAS;GAAa;GACzE,OAAO,EAAE,GAAG,EAAE,MAAM,cAAc,IAAI,GAAG,EAAE,QAAQ,YAAY,CAAC;GAChE,QAAQ;IAAC;IAAU;IAAe;GAAsB,CAAC,CAAC,KAAK,SAC3D,EAAE,YAAY,MAAM,EAAE,MAAM,cAAc,IAAI,CAAC,CACnD;EACJ,CAAC,CACL,EACJ,CAAC;EAYD,MAAM,OAAM,OAXQ,OAAO,oBAAoB,OAAO,MAAM,KAAK,CAAC,CAAC,CAAC,OAAO,WAAW,CAAC,CAAC,KACpF,OAAO,eAEC,IAAI,aAAa;GACb,WAAW;GACX,MAAM;GACN,WAAW;GACX,SAAS;EACb,CAAC,CACT,CACJ,EAAA,CACiB;EACjB,IAAI,CAAC,KACD,OAAO,OAAO,IAAI,aAAa;GAC3B,WAAW;GACX,MAAM;GACN,WAAW;GACX,SAAS;EACb,CAAC;EACL,OAAO;CACX,CAAC;CACD,IAAI,UAAU,OAAO,KAAK;CAC1B,MAAM,MAAM,OAAO,MAAM;CAEzB,IACI,CAAC,QAAQ,eACT,QAAQ,WAAW,cAClB,QAAQ,wBAAwB,QAAQ,qBAAqB,qBAAqB,MAAM,KAC3F;EACE,OAAO,QAAQ,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"}
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 const now = yield* Clock.currentTimeMillis;\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 if (\n !current.accessToken ||\n current.status === \"inactive\" ||\n (current.accessTokenExpiresAt &&\n current.accessTokenExpiresAt.epochMilliseconds <= now + accessTokenRenewalWindowMs)\n ) {\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;AAC1C,MAAM,QAAQ,OAAO,OAAO;CACxB,QAAQ,OAAO,SAAS;EAAC;EAAU;EAAc;CAAU,CAAC;CAC5D,aAAa,OAAO,SAAS,oBAAoB;CACjD,sBAAsB,OAAO,SAAS,iBAAiB;AAC3D,CAAC;;;;;AAMD,MAAa,wBAAwB,OAAO,GAAG,qBAAqB,CAAC,CAAC,WAClE,SACA,cACF;CACE,IAAI,CAAC,QAAQ,WACT,OAAO,OAAO,IAAI,aAAa;EAC3B,WAAW;EACX,MAAM;EACN,WAAW;EACX,SAAS;CACb,CAAC;CACL,MAAM,OAAO,OAAO,WAAW,aAAa;EACxC,MAAM,SAAS,OAAO,QAAQ,MAAM,EAChC,QAAQ,CACJ,EAAE,IAAI,eAAe;GACjB,MAAM;IAAE,QAAQ,EAAE,YAAY,kBAAkB;IAAG,SAAS;GAAa;GACzE,OAAO,EAAE,GAAG,EAAE,MAAM,cAAc,IAAI,GAAG,EAAE,QAAQ,YAAY,CAAC;GAChE,QAAQ;IAAC;IAAU;IAAe;GAAsB,CAAC,CAAC,KAAK,SAC3D,EAAE,YAAY,MAAM,EAAE,MAAM,cAAc,IAAI,CAAC,CACnD;EACJ,CAAC,CACL,EACJ,CAAC;EAYD,MAAM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A;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;;EAElD,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"}
@@ -21,6 +21,41 @@ const guardUrl = (value) => Effect.try({
21
21
  },
22
22
  catch: () => connectError("Configuration", "OAuth URLs require HTTPS (or HTTP on localhost).")
23
23
  });
24
+ const unsafeRedirectSchemes = /* @__PURE__ */ new Set([
25
+ "about:",
26
+ "blob:",
27
+ "data:",
28
+ "file:",
29
+ "filesystem:",
30
+ "ftp:",
31
+ "javascript:",
32
+ "vbscript:",
33
+ "ws:",
34
+ "wss:"
35
+ ]);
36
+ const nativeRedirect = (url) => /^[a-z][a-z0-9+.-]*:$/.test(url.protocol) && url.protocol !== "http:" && url.protocol !== "https:" && !unsafeRedirectSchemes.has(url.protocol) && !url.username && !url.password && !url.port && !url.hash;
37
+ /** Network redirects keep the HTTPS policy. A native application may instead
38
+ * receive its callback at a custom scheme, but only at the exact redirect its
39
+ * trusted OAuth application registration declares; callers cannot introduce one.
40
+ */
41
+ const guardRedirectUrl = (value, registered) => Effect.try({
42
+ try: () => {
43
+ const url = new URL(value);
44
+ if (url.protocol === "https:" || url.protocol === "http:" && [
45
+ "localhost",
46
+ "127.0.0.1",
47
+ "[::1]"
48
+ ].includes(url.hostname)) return url;
49
+ if (registered !== void 0 && value === registered && nativeRedirect(url)) return url;
50
+ throw new Error();
51
+ },
52
+ catch: () => connectError("Configuration", "OAuth redirect URLs require HTTPS, HTTP on localhost, or the application's registered native redirect.")
53
+ });
54
+ /** Callback URLs are parsed before the attempt is known; its accepted redirect
55
+ * then decides the exact scheme, host and path. URL.origin is "null" for custom
56
+ * schemes, so compare those parts explicitly.
57
+ */
58
+ const sameRedirectTarget = (expected, callback) => expected.protocol === callback.protocol && expected.host === callback.host && expected.pathname === callback.pathname && expected.username === callback.username && expected.password === callback.password;
24
59
  /** One credential authority, usable by both device and HTTP entry points. */
25
60
  const makeOAuthAuthority = (options) => Effect.sync(() => {
26
61
  const { store, values } = options;
@@ -136,9 +171,9 @@ const makeOAuthAuthority = (options) => Effect.sync(() => {
136
171
  return connection;
137
172
  }),
138
173
  begin: Effect.fn("Connect.begin")(function* (input) {
139
- yield* guardUrl(input.redirectUrl);
140
174
  if (input.returnUrl) yield* guardUrl(input.returnUrl);
141
175
  const { application, oauth } = yield* configured(input.applicationId);
176
+ yield* guardRedirectUrl(input.redirectUrl, application.redirectUrl);
142
177
  if (application.redirectUrl && input.redirectUrl !== application.redirectUrl) return yield* connectError("Forbidden", "Redirect URL does not match the OAuth application.");
143
178
  if (application.flow !== "authorization-code") return yield* connectError("Configuration", "This application does not support interactive authorization.");
144
179
  const id = oauth4webapi.generateRandomState();
@@ -178,14 +213,17 @@ const makeOAuthAuthority = (options) => Effect.sync(() => {
178
213
  };
179
214
  }),
180
215
  complete: Effect.fn("Connect.complete")(function* (input) {
181
- const callback = yield* guardUrl(input.callbackUrl);
216
+ const callback = yield* Effect.try({
217
+ try: () => new URL(input.callbackUrl),
218
+ catch: () => connectError("InvalidAttempt", "Authorization callback URL is invalid.")
219
+ });
182
220
  const id = callback.searchParams.get("state");
183
221
  if (!id) return yield* connectError("InvalidAttempt", "Authorization attempt is unavailable.");
184
222
  const attempt = yield* store.transaction(Effect.gen(function* () {
185
223
  const current = yield* store.get("OAuthAuthorizationAttempt", id);
186
224
  if (!current || current.principalId !== input.principalId || expired(current.expiresAt, yield* Clock.currentTimeMillis)) return yield* connectError("InvalidAttempt", "Authorization attempt is unavailable.");
187
225
  const expected = new URL(current.redirectUrl);
188
- if (expected.origin !== callback.origin || expected.pathname !== callback.pathname) return yield* connectError("InvalidAttempt", "Authorization callback URL does not match.");
226
+ if (!sameRedirectTarget(expected, callback)) return yield* connectError("InvalidAttempt", "Authorization callback URL does not match.");
189
227
  if (current.status === "completed") return current;
190
228
  if (current.status !== "pending") return yield* connectError("InvalidAttempt", "Authorization attempt was already consumed; start again.");
191
229
  yield* store.put("OAuthAuthorizationAttempt", {
@@ -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/** One credential authority, usable by both device and HTTP entry points. */\nexport const makeOAuthAuthority = (options: OAuthAuthorityOptions): Effect.Effect<OAuthAuthorityService> =>\n Effect.sync(() => {\n const { store, values } = options;\n const read = Effect.fnUntraced(function* (id: string) {\n const record = yield* store.get(\"OAuthConnection\", id);\n if (!record) return yield* connectError(\"NotFound\", \"Connection is unavailable.\");\n return record;\n });\n const configured = Effect.fnUntraced(function* (id: string) {\n const application = yield* store.get(\"OAuthApplication\", id);\n if (!application) return yield* connectError(\"NotFound\", \"OAuth application is unavailable.\");\n const serviceInstance = yield* store.get(\"ServiceInstance\", application.serviceInstance);\n if (!serviceInstance) return yield* connectError(\"NotFound\", \"Service instance is unavailable.\");\n return { application, oauth: yield* options.oauth({ application, serviceInstance }) };\n });\n const decrypt = (value: Encrypted<string>) =>\n values.decrypt(Schema.String, value).pipe(\n Effect.map(Redacted.make),\n Effect.mapError(() => connectError(\"Storage\", \"Credential decryption failed.\"))\n );\n const encrypt = (value: string) =>\n values\n .encrypt(Schema.String, value)\n .pipe(Effect.mapError(() => connectError(\"Storage\", \"Credential encryption failed.\")));\n const evict = (value: Encrypted<string> | undefined) =>\n value\n ? values\n .evict(value)\n .pipe(\n Effect.mapError(() => connectError(\"Storage\", \"Credential deletion failed.\", true))\n )\n : Effect.void;\n const saveTokens = Effect.fnUntraced(function* (record: OAuthConnectionRecord, tokens: OAuthTokens) {\n if (record.userId && record.userId !== tokens.userId)\n return yield* connectError(\n \"NeedsAuthentication\",\n \"Provider identity changed; reconnect explicitly.\"\n );\n const next: OAuthConnectionRecord = {\n ...record,\n status: \"active\",\n userId: tokens.userId,\n accessToken: yield* encrypt(tokens.accessToken),\n accessTokenExpiresAt: tokens.accessTokenExpiresAt,\n refreshToken: tokens.refreshToken ? yield* encrypt(tokens.refreshToken) : undefined,\n refreshTokenExpiresAt: tokens.refreshToken ? tokens.refreshTokenExpiresAt : undefined,\n grantedScopes: tokens.grantedScopes,\n operationId: undefined,\n operationExpiresAt: undefined,\n };\n yield* store.put(\"OAuthConnection\", next);\n yield* evict(record.accessToken);\n yield* evict(record.refreshToken);\n return next;\n });\n const busy = Effect.fnUntraced(function* (record: OAuthConnectionRecord, recovery = false) {\n if (!record.operationId) return;\n const now = yield* Clock.currentTimeMillis;\n if (!expired(record.operationExpiresAt, now))\n return yield* connectError(\"Busy\", \"Connection operation is in progress.\", true);\n if (recovery) return;\n // A refresh may have rotated the token before its reply was lost. Never retry blindly.\n return yield* connectError(\n \"NeedsAuthentication\",\n \"An interrupted credential operation requires reconnection.\"\n );\n });\n const finish = Effect.fnUntraced(function* (record: OAuthConnectionRecord, id: string) {\n const current = yield* read(record.id);\n if (current.operationId !== id)\n return yield* connectError(\"Busy\", \"Connection changed during the credential operation.\");\n return current;\n });\n const refresh = Effect.fn(\"Connect.refresh\")(function* (connectionId: string) {\n const operationId = crypto.randomUUID();\n const record = yield* store.transaction(\n Effect.gen(function* () {\n const current = yield* read(connectionId);\n yield* busy(current);\n if (current.status !== \"active\")\n return yield* connectError(\"NeedsAuthentication\", \"Reconnect this connection.\");\n const next = {\n ...current,\n operationId,\n operationExpiresAt: instant((yield* Clock.currentTimeMillis) + 60_000),\n };\n yield* store.put(\"OAuthConnection\", next);\n return next;\n })\n );\n const request = Effect.gen(function* () {\n const { application, oauth } = yield* configured(record.application);\n let tokens: OAuthTokens;\n if (application.flow === \"client-credentials\") tokens = yield* oauth.clientCredentials;\n else {\n if (\n !record.refreshToken ||\n expired(record.refreshTokenExpiresAt, yield* Clock.currentTimeMillis)\n )\n return yield* connectError(\n \"NeedsAuthentication\",\n \"Refresh credentials are unavailable or expired.\"\n );\n tokens = yield* oauth.refresh(Redacted.value(yield* decrypt(record.refreshToken)));\n if (!tokens.refreshToken)\n tokens = {\n ...tokens,\n refreshToken: Redacted.value(yield* decrypt(record.refreshToken)),\n refreshTokenExpiresAt: record.refreshTokenExpiresAt,\n };\n }\n return yield* store.transaction(\n Effect.gen(function* () {\n const current = yield* finish(record, operationId);\n return yield* saveTokens(current, tokens);\n })\n );\n }).pipe(\n Effect.timeout(45_000),\n Effect.catchTag(\"TimeoutError\", () =>\n Effect.fail(\n connectError(\n \"NeedsAuthentication\",\n \"Credential exchange timed out; reconnect before retrying.\"\n )\n )\n )\n );\n return yield* request.pipe(\n Effect.catch((error) =>\n store\n .transaction(\n Effect.gen(function* () {\n const current = yield* finish(record, operationId);\n if (error.kind === \"NeedsAuthentication\") {\n yield* evict(current.refreshToken);\n yield* store.put(\"OAuthConnection\", {\n ...current,\n refreshToken: undefined,\n refreshTokenExpiresAt: undefined,\n status: \"needs-auth\",\n operationId: undefined,\n operationExpiresAt: undefined,\n });\n } else if (error.kind !== \"Storage\")\n yield* store.put(\"OAuthConnection\", {\n ...current,\n operationId: undefined,\n operationExpiresAt: undefined,\n });\n })\n )\n .pipe(Effect.andThen(Effect.fail(error)))\n )\n );\n });\n return OAuthAuthority.of({\n connectionForApplication: Effect.fn(\"Connect.connectionForApplication\")(function* (\n applicationId: string\n ) {\n const application = yield* store.get(\"OAuthApplication\", applicationId);\n if (!application) return yield* connectError(\"NotFound\", \"OAuth application is unavailable.\");\n if (!application.connection) return;\n const connection = yield* read(application.connection);\n if (connection.application !== applicationId)\n return yield* connectError(\n \"Configuration\",\n \"OAuth application points to a connection belonging to another application.\"\n );\n return connection;\n }),\n begin: Effect.fn(\"Connect.begin\")(function* (input: BeginAuthorization) {\n yield* guardUrl(input.redirectUrl);\n if (input.returnUrl) yield* guardUrl(input.returnUrl);\n const { application, oauth } = yield* configured(input.applicationId);\n if (application.redirectUrl && input.redirectUrl !== application.redirectUrl)\n return yield* connectError(\n \"Forbidden\",\n \"Redirect URL does not match the OAuth application.\"\n );\n if (application.flow !== \"authorization-code\")\n return yield* connectError(\n \"Configuration\",\n \"This application does not support interactive authorization.\"\n );\n const id = oauth4webapi.generateRandomState();\n const verifier = oauth4webapi.generateRandomCodeVerifier();\n const challenge = yield* Effect.tryPromise({\n try: () => oauth4webapi.calculatePKCECodeChallenge(verifier),\n catch: () => connectError(\"Configuration\", \"Could not generate PKCE challenge.\"),\n });\n const authorizationUrl = yield* oauth.authorizationUrl({\n state: id,\n codeChallenge: challenge,\n redirectUrl: input.redirectUrl,\n });\n yield* guardUrl(authorizationUrl);\n yield* store.transaction(\n Effect.gen(function* () {\n if (input.connectionId) {\n const previous = yield* read(input.connectionId);\n if (previous.application !== input.applicationId)\n return yield* connectError(\n \"Forbidden\",\n \"Connection belongs to another application.\"\n );\n yield* busy(previous, true);\n }\n yield* store.put(\"OAuthAuthorizationAttempt\", {\n ...input.properties,\n id,\n application: input.applicationId,\n principalId: input.principalId,\n connectionId: input.connectionId ?? crypto.randomUUID(),\n redirectUrl: input.redirectUrl,\n returnUrl: input.returnUrl,\n codeVerifier: yield* encrypt(verifier),\n expiresAt: instant((yield* Clock.currentTimeMillis) + 600_000),\n status: \"pending\",\n });\n })\n );\n return { id, authorizationUrl };\n }),\n complete: Effect.fn(\"Connect.complete\")(function* (input: {\n callbackUrl: string;\n principalId?: string;\n }) {\n const callback = yield* guardUrl(input.callbackUrl);\n const id = callback.searchParams.get(\"state\");\n if (!id)\n return yield* connectError(\"InvalidAttempt\", \"Authorization attempt is unavailable.\");\n const attempt = yield* store.transaction(\n Effect.gen(function* () {\n const current = yield* store.get(\"OAuthAuthorizationAttempt\", id);\n if (\n !current ||\n current.principalId !== input.principalId ||\n expired(current.expiresAt, yield* Clock.currentTimeMillis)\n )\n return yield* connectError(\n \"InvalidAttempt\",\n \"Authorization attempt is unavailable.\"\n );\n const expected = new URL(current.redirectUrl);\n if (expected.origin !== callback.origin || expected.pathname !== callback.pathname)\n return yield* connectError(\n \"InvalidAttempt\",\n \"Authorization callback URL does not match.\"\n );\n if (current.status === \"completed\") return current;\n if (current.status !== \"pending\")\n return yield* connectError(\n \"InvalidAttempt\",\n \"Authorization attempt was already consumed; start again.\"\n );\n yield* store.put(\"OAuthAuthorizationAttempt\", { ...current, status: \"exchanging\" });\n return current;\n })\n );\n if (attempt.status === \"completed\") {\n if (!attempt.connectionId)\n return yield* connectError(\n \"InvalidAttempt\",\n \"Completed authorization has no connection.\"\n );\n return yield* read(attempt.connectionId);\n }\n const exchange = Effect.gen(function* () {\n const { application, oauth } = yield* configured(attempt.application);\n const tokens = yield* oauth.exchange({\n callbackUrl: input.callbackUrl,\n state: id,\n redirectUrl: attempt.redirectUrl,\n codeVerifier: Redacted.value(yield* decrypt(attempt.codeVerifier)),\n });\n const extra = options.connectionProperties\n ? yield* options.connectionProperties(attempt)\n : {};\n return yield* store.transaction(\n Effect.gen(function* () {\n const claimed = yield* store.get(\"OAuthAuthorizationAttempt\", id);\n if (!claimed || claimed.status !== \"exchanging\")\n return yield* connectError(\n \"InvalidAttempt\",\n \"Authorization attempt is no longer available.\"\n );\n const requested = yield* store.get(\"OAuthConnection\", attempt.connectionId);\n const matches = requested\n ? []\n : yield* store.load(\"OAuthConnection\", {\n where: and(\n eq(field(\"application\"), attempt.application),\n eq(field(\"userId\"), tokens.userId)\n ),\n });\n // Trusted application ownership fields participate in reuse;\n // two projects/principals can still keep separate bindings.\n const reusable = matches.find((row) =>\n Object.entries(extra).every(\n ([name, value]) =>\n JSON.stringify((row as Record<string, unknown>)[name]) ===\n JSON.stringify(value)\n )\n );\n const connectionId = requested?.id ?? reusable?.id ?? attempt.connectionId;\n const current = yield* store.get(\"OAuthConnection\", connectionId);\n if (current) {\n if (current.application !== attempt.application)\n return yield* connectError(\n \"Forbidden\",\n \"Connection belongs to another application.\"\n );\n }\n // A completed login supersedes an in-flight refresh. Clearing\n // operationId fences its late result in finish().\n const next = yield* saveTokens(\n {\n ...extra,\n ...current,\n id: connectionId,\n application: attempt.application,\n title: current?.title ?? application.title,\n status: \"active\",\n },\n tokens\n );\n const latestConnector = yield* store.get(\"OAuthApplication\", application.id);\n if (!latestConnector)\n return yield* connectError(\"NotFound\", \"OAuth application is unavailable.\");\n yield* store.put(\"OAuthApplication\", { ...latestConnector, connection: next.id });\n yield* store.put(\"OAuthAuthorizationAttempt\", {\n ...attempt,\n connectionId: next.id,\n status: \"completed\",\n });\n yield* evict(attempt.codeVerifier);\n return next;\n })\n );\n }).pipe(\n Effect.timeout(45_000),\n Effect.catchTag(\"TimeoutError\", () =>\n Effect.fail(\n connectError(\"Provider\", \"Authorization exchange timed out; start again.\")\n )\n )\n );\n return yield* exchange.pipe(\n Effect.catch((error) =>\n Effect.andThen(\n store.transaction(\n Effect.gen(function* () {\n const claimed = yield* store.get(\"OAuthAuthorizationAttempt\", id);\n if (!claimed || claimed.status !== \"exchanging\") return;\n yield* store.put(\"OAuthAuthorizationAttempt\", {\n ...attempt,\n status: \"failed\",\n });\n yield* evict(attempt.codeVerifier);\n })\n ),\n Effect.fail(error)\n )\n )\n );\n }),\n clientCredentials: Effect.fn(\"Connect.clientCredentials\")(function* (input: {\n applicationId: string;\n connectionId?: string;\n properties?: Record<string, unknown>;\n }) {\n const { application } = yield* configured(input.applicationId);\n if (application.flow !== \"client-credentials\")\n return yield* connectError(\n \"Configuration\",\n \"This application does not use client credentials.\"\n );\n const connectionId = input.connectionId ?? application.connection ?? crypto.randomUUID();\n yield* store.transaction(\n Effect.gen(function* () {\n const existing = yield* store.get(\"OAuthConnection\", connectionId);\n if (existing && existing.application !== application.id)\n return yield* connectError(\n \"Forbidden\",\n \"Connection belongs to another application.\"\n );\n if (existing) yield* busy(existing);\n yield* store.put(\"OAuthConnection\", {\n ...input.properties,\n ...existing,\n id: connectionId,\n title: existing?.title ?? application.title,\n application: application.id,\n status: \"active\",\n });\n const latest = yield* store.get(\"OAuthApplication\", application.id);\n if (!latest)\n return yield* connectError(\"NotFound\", \"OAuth application is unavailable.\");\n yield* store.put(\"OAuthApplication\", { ...latest, connection: connectionId });\n })\n );\n return yield* refresh(connectionId);\n }),\n refresh,\n disconnect: Effect.fn(\"Connect.disconnect\")(function* (id: string) {\n // Detach credentials atomically first. Revocation failure must not restore local access.\n const record = yield* store.transaction(\n Effect.gen(function* () {\n const current = yield* read(id);\n const token = current.refreshToken ?? current.accessToken;\n const plaintext = token\n ? yield* decrypt(token).pipe(Effect.catch(() => Effect.succeed(undefined)))\n : undefined;\n yield* store.put(\"OAuthConnection\", {\n ...current,\n status: \"inactive\",\n operationId: undefined,\n operationExpiresAt: undefined,\n accessToken: undefined,\n accessTokenExpiresAt: undefined,\n refreshToken: undefined,\n refreshTokenExpiresAt: undefined,\n });\n yield* evict(current.accessToken);\n yield* evict(current.refreshToken);\n return { current, plaintext };\n })\n );\n if (record.plaintext) {\n const { oauth } = yield* configured(record.current.application);\n if (oauth.revoke) yield* oauth.revoke(Redacted.value(record.plaintext));\n }\n }),\n forget: Effect.fn(\"Connect.forget\")(function* (id: string) {\n const removed = yield* store.transaction(\n Effect.gen(function* () {\n const current = yield* store.get(\"OAuthConnection\", id);\n const token = current?.refreshToken ?? current?.accessToken;\n const plaintext = token\n ? yield* decrypt(token).pipe(Effect.catch(() => Effect.succeed(undefined)))\n : undefined;\n const attempts = yield* store.load(\"OAuthAuthorizationAttempt\", {\n where: eq(field(\"connectionId\"), id),\n });\n for (const attempt of attempts) {\n yield* evict(attempt.codeVerifier);\n yield* store.delete(\"OAuthAuthorizationAttempt\", attempt.id);\n }\n const applications = yield* store.load(\"OAuthApplication\", {\n where: eq(field(\"connection\"), id),\n });\n for (const application of applications)\n yield* store.put(\"OAuthApplication\", { ...application, connection: undefined });\n if (current) {\n yield* evict(current.accessToken);\n yield* evict(current.refreshToken);\n yield* store.delete(\"OAuthConnection\", id);\n }\n return { current, plaintext };\n })\n );\n // Local deletion commits before remote revocation, including when\n // revocation fails. Action reference validation remains at the boundary.\n if (removed.current && removed.plaintext) {\n const { oauth } = yield* configured(removed.current.application);\n if (oauth.revoke) yield* oauth.revoke(Redacted.value(removed.plaintext));\n }\n }),\n collectExpired: Effect.fn(\"Connect.collectExpired\")(function* ({\n limit = 100,\n }: { limit?: number } = {}) {\n if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1000)\n return yield* connectError(\"Configuration\", \"GC batch size must be between 1 and 1000.\");\n return yield* store.transaction(\n Effect.gen(function* () {\n const now = instant(yield* Clock.currentTimeMillis);\n const attempts = yield* store.load(\"OAuthAuthorizationAttempt\", {\n where: lte(field(\"expiresAt\"), now),\n orderBy: [{ field: field(\"expiresAt\") }],\n limit,\n });\n for (const attempt of attempts) {\n yield* evict(attempt.codeVerifier);\n yield* store.delete(\"OAuthAuthorizationAttempt\", attempt.id);\n }\n const connections = yield* store.load(\"OAuthConnection\", {\n where: and(\n ne(field(\"refreshTokenExpiresAt\"), undefined),\n lte(field(\"refreshTokenExpiresAt\"), now),\n eq(field(\"operationId\"), undefined)\n ),\n orderBy: [{ field: field(\"refreshTokenExpiresAt\") }],\n limit,\n });\n for (const record of connections) {\n yield* evict(record.refreshToken);\n yield* store.put(\"OAuthConnection\", {\n ...record,\n refreshToken: undefined,\n refreshTokenExpiresAt: undefined,\n status: \"needs-auth\",\n });\n }\n // External sessions can be extended upstream. Revalidate\n // them on demand instead of declaring a cached expiry final.\n const expiredConnections = yield* store.load(\"ApiKeyConnection\", {\n where: and(\n eq(field(\"status\"), \"active\"),\n ne(field(\"expiresAt\"), undefined),\n lte(field(\"expiresAt\"), now)\n ),\n orderBy: [{ field: field(\"expiresAt\") }],\n limit,\n });\n for (const record of expiredConnections)\n yield* store.put(\"ApiKeyConnection\", { ...record, status: \"needs-auth\" });\n return { attempts: attempts.length, refreshTokens: connections.length };\n })\n );\n }),\n });\n });\n"],"mappings":";;;;;;AAsFA,IAAa,iBAAb,MAAa,uBAAuB,QAAQ,QAA+C,CAAC,CACxF,qCACJ,CAAC,CAAC;CACE,OAAgB,SAAS,YACrB,MAAM,OAAO,gBAAgB,mBAAmB,OAAO,CAAC;AAChE;AACA,MAAM,WAAW,iBAAyB,SAAS,QAAQ,sBAAsB,YAAY;AAC7F,MAAM,WAAW,MAAoC,QACjD,SAAS,KAAA,KAAa,KAAK,qBAAqB;AACpD,MAAM,YAAY,UACd,OAAO,IAAI;CACP,WAAW;EACP,MAAM,MAAM,IAAI,IAAI,KAAK;EACzB,IACI,IAAI,aAAa,YACjB,EAAE,IAAI,aAAa,WAAW;GAAC;GAAa;GAAa;EAAO,CAAC,CAAC,SAAS,IAAI,QAAQ,IAEvF,MAAM,IAAI,MAAM;EACpB,OAAO;CACX;CACA,aAAa,aAAa,iBAAiB,kDAAkD;AACjG,CAAC;;AAGL,MAAa,sBAAsB,YAC/B,OAAO,WAAW;CACd,MAAM,EAAE,OAAO,WA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AAW,GAAG,GAAG;KAClC,SAAS,CAAC,EAAE,OAAO,MAAM,WAAW,EAAE,CAAC;KACvC;IACJ,CAAC;IACD,KAAK,MAAM,WAAW,UAAU;KAC5B,OAAO,MAAM,QAAQ,YAAY;KACjC,OAAO,MAAM,OAAO,6BAA6B,QAAQ,EAAE;IAC/D;IACA,MAAM,cAAc,OAAO,MAAM,KAAK,mBAAmB;KACrD,OAAO,IACH,GAAG,MAAM,uBAAuB,GAAG,KAAA,CAAS,GAC5C,IAAI,MAAM,uBAAuB,GAAG,GAAG,GACvC,GAAG,MAAM,aAAa,GAAG,KAAA,CAAS,CACtC;KACA,SAAS,CAAC,EAAE,OAAO,MAAM,uBAAuB,EAAE,CAAC;KACnD;IACJ,CAAC;IACD,KAAK,MAAM,UAAU,aAAa;KAC9B,OAAO,MAAM,OAAO,YAAY;KAChC,OAAO,MAAM,IAAI,mBAAmB;MAChC,GAAG;MACH,cAAc,KAAA;MACd,uBAAuB,KAAA;MACvB,QAAQ;KACZ,CAAC;IACL;IAGA,MAAM,qBAAqB,OAAO,MAAM,KAAK,oBAAoB;KAC7D,OAAO,IACH,GAAG,MAAM,QAAQ,GAAG,QAAQ,GAC5B,GAAG,MAAM,WAAW,GAAG,KAAA,CAAS,GAChC,IAAI,MAAM,WAAW,GAAG,GAAG,CAC/B;KACA,SAAS,CAAC,EAAE,OAAO,MAAM,WAAW,EAAE,CAAC;KACvC;IACJ,CAAC;IACD,KAAK,MAAM,UAAU,oBACjB,OAAO,MAAM,IAAI,oBAAoB;KAAE,GAAG;KAAQ,QAAQ;IAAa,CAAC;IAC5E,OAAO;KAAE,UAAU,SAAS;KAAQ,eAAe,YAAY;IAAO;GAC1E,CAAC,CACL;EACJ,CAAC;CACL,CAAC;AACL,CAAC"}
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,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,K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uBAAuB,EAAE,CAAC;KACnD;IACJ,CAAC;IACD,KAAK,MAAM,UAAU,aAAa;KAC9B,OAAO,MAAM,OAAO,YAAY;KAChC,OAAO,MAAM,IAAI,mBAAmB;MAChC,GAAG;MACH,cAAc,KAAA;MACd,uBAAuB,KAAA;MACvB,QAAQ;KACZ,CAAC;IACL;IAGA,MAAM,qBAAqB,OAAO,MAAM,KAAK,oBAAoB;KAC7D,OAAO,IACH,GAAG,MAAM,QAAQ,GAAG,QAAQ,GAC5B,GAAG,MAAM,WAAW,GAAG,KAAA,CAAS,GAChC,IAAI,MAAM,WAAW,GAAG,GAAG,CAC/B;KACA,SAAS,CAAC,EAAE,OAAO,MAAM,WAAW,EAAE,CAAC;KACvC;IACJ,CAAC;IACD,KAAK,MAAM,UAAU,oBACjB,OAAO,MAAM,IAAI,oBAAoB;KAAE,GAAG;KAAQ,QAAQ;IAAa,CAAC;IAC5E,OAAO;KAAE,UAAU,SAAS;KAAQ,eAAe,YAAY;IAAO;GAC1E,CAAC,CACL;EACJ,CAAC;CACL,CAAC;AACL,CAAC"}
package/lib/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { ConnectError } from "./core/errors.js";
2
2
  import { ConnectStore, makeConnectStore } from "./core/store.js";
3
3
  import { BeginAuthorization, ConnectCredentialValues, ConnectOAuthService, OAuthTokens } from "./core/oauthAuthority.js";
4
- import { Connection, ConnectionEgress, ConnectionEgressHandlers, ConnectionMonitor, ConnectionState, ConnectionStateSchema, ConnectionStatus } from "./types.js";
4
+ import { Connection, ConnectionEgress, ConnectionEgressHandlers, ConnectionLifecycle, ConnectionMonitor, ConnectionState, ConnectionStateSchema, ConnectionStatus } from "./types.js";
5
5
  import { ConnectionRef, SavedConnection, ServiceConnector, VerifiedServiceIdentity } from "./ServiceConnector.js";
6
6
  import { createDefaultConnectionEgressHandlers } from "./createDefaultConnectionEgressHandlers.js";
7
7
  import { withHttpAuthenticationErrors } from "./withHttpAuthenticationErrors.js";
@@ -17,4 +17,4 @@ import { ConnectionAccess } from "./serviceConnections.js";
17
17
  import { toWebEgress } from "./toWebEgress.js";
18
18
  import { ConnectInstanceConfiguration, ConnectManager, ConnectManagerOptions, ConnectManagerService, ConnectOAuthApplicationConfiguration, ConnectServiceConfiguration, makeConnectManager } from "./makeConnectManager.js";
19
19
  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 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, connectionAccessToken, createDefaultConnectionEgressHandlers, makeAuthenticationClient, makeConnectBackend, makeConnectManager, makeConnectStore, makeOAuthAuthorizationClient, makeOAuthService, makeServerConnectClient, oauthAuthorizationOntology, runtimeCredentialValues, toWebEgress, withHttpAuthenticationErrors };
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, connectionAccessToken, createDefaultConnectionEgressHandlers, makeAuthenticationClient, makeConnectBackend, makeConnectManager, makeConnectStore, makeOAuthAuthorizationClient, makeOAuthService, makeServerConnectClient, oauthAuthorizationOntology, runtimeCredentialValues, toWebEgress, withHttpAuthenticationErrors };
@@ -1,7 +1,7 @@
1
1
  import { OAuthApplicationRecord, ServiceInstanceRecord } from "./spec/index.js";
2
2
  import { ConnectStore } from "./core/store.js";
3
3
  import { ConnectCredentialValues, OAuthAuthorityService } from "./core/oauthAuthority.js";
4
- import { ConnectionEgress, ConnectionMonitor } from "./types.js";
4
+ import { ConnectionEgress, ConnectionLifecycle } from "./types.js";
5
5
  import { ConnectionRef, ServiceConnector } from "./ServiceConnector.js";
6
6
  import { ConnectActionHandler } from "./core/backend.js";
7
7
  import "./index.js";
@@ -53,7 +53,7 @@ export declare const makeConnectManager: (options: ConnectManagerOptions) => Eff
53
53
  userId: string;
54
54
  serviceInstance: ServiceInstanceRecord;
55
55
  egress: ConnectionEgress;
56
- authentication: ConnectionMonitor;
56
+ authentication: ConnectionLifecycle;
57
57
  }, BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, import("effect/Scope").Scope>;
58
58
  };
59
59
  maintenance: {
@@ -75,7 +75,7 @@ declare const ConnectManager_base: Context.ServiceClass<ConnectManager, "@party-
75
75
  userId: string;
76
76
  serviceInstance: ServiceInstanceRecord;
77
77
  egress: ConnectionEgress;
78
- authentication: ConnectionMonitor;
78
+ authentication: ConnectionLifecycle;
79
79
  }, BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, import("effect/Scope").Scope>;
80
80
  };
81
81
  maintenance: {
@@ -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.ConnectionMonitor"],"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;;;;;;;;;;;;;;;;IA2EgC,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"}
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;;;;;;;;;;;;;;;;IA2EgC,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"}
@@ -1,6 +1,6 @@
1
1
  import { ServiceInstanceRecord } from "./spec/index.js";
2
2
  import { ConnectStore } from "./core/store.js";
3
- import { ConnectionEgress, ConnectionEgressHandlers, ConnectionMonitor } from "./types.js";
3
+ import { ConnectionEgress, ConnectionEgressHandlers, ConnectionLifecycle } from "./types.js";
4
4
  import { ConnectionRef, ServiceConnector } from "./ServiceConnector.js";
5
5
  import { BackendError, OntologyBackendService } from "@party-stack/ontology-backend";
6
6
  import { Effect } from "effect";
@@ -13,7 +13,8 @@ export interface ConnectionAccess {
13
13
  readonly userId: string;
14
14
  readonly serviceInstance: ServiceInstanceRecord;
15
15
  readonly egress: ConnectionEgress;
16
- readonly authentication: ConnectionMonitor;
16
+ /** Pass to the replica that syncs this connection; show apps only its monitor fields. */
17
+ readonly authentication: ConnectionLifecycle;
17
18
  }
18
19
  /** Acquire saved identity and egress from ontology records. The map holds only
19
20
  * scoped access; the Connect backend remains the sole durable inventory.
@@ -32,7 +33,7 @@ export declare const makeServiceConnections: (options: {
32
33
  userId: string;
33
34
  serviceInstance: ServiceInstanceRecord;
34
35
  egress: ConnectionEgress;
35
- authentication: ConnectionMonitor;
36
+ authentication: ConnectionLifecycle;
36
37
  }, BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, import("effect/Scope").Scope>;
37
38
  }, BackendError<"InvalidConfiguration">, import("effect/Scope").Scope>;
38
39
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"serviceConnections.d.ts","names":[],"sources":["../src/serviceConnections.ts"],"mappings":";;;;;;;;;;iBAsBiB;WACJ,YAAY;WACZ;WACA,iBAAiB;WACjB,QAAQ;WACR,gBAAgB;;;;;qBAqBhB,yBAAsB;WACb,SAAA;WACF,OAAA;WACG,mBAAS;WACR,WAAA;;EAgZM,UAAA,YAAA,kBAAa,OAAA;;;;;;IAPS,iBAAA;;;;GASlD,6DAAA"}
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;;EAsdM,UAAA,YAAA,kBAAa,OAAA;;;;;;IAPS,iBAAA;;;;GASlD,6DAAA"}
@@ -14,6 +14,21 @@ const unavailable = (message) => new BackendError({
14
14
  message
15
15
  });
16
16
  const CredentialObserver = Context.Reference("@party-stack/connect/CredentialObserver", { defaultValue: () => () => {} });
17
+ const retryAfterRenewal = () => new BackendError({
18
+ operation: "connect.egress",
19
+ kind: "Unavailable",
20
+ retryable: true,
21
+ actionOutcome: "not-committed",
22
+ message: "The credential was renewed after the service rejected it; retry the request."
23
+ });
24
+ const renewalUnavailable = (cause) => new BackendError({
25
+ operation: "connect.refresh",
26
+ kind: "Unavailable",
27
+ retryable: true,
28
+ actionOutcome: "not-committed",
29
+ message: "The rejected credential could not be renewed yet; retry the request.",
30
+ cause
31
+ });
17
32
  /** Acquire saved identity and egress from ontology records. The map holds only
18
33
  * scoped access; the Connect backend remains the sole durable inventory.
19
34
  */
@@ -144,11 +159,22 @@ const makeServiceConnections = Effect.fn("Connect.connections")(function* (optio
144
159
  state = value;
145
160
  for (const listener of listeners) listener(value);
146
161
  };
162
+ const credentialIdentity = (value) => JSON.stringify(!value ? null : [
163
+ value.status,
164
+ value.userId,
165
+ "application" in value ? value.accessToken?.ciphertext : "sessionId" in value ? [value.sessionId, value.expiresAt] : [value.apiKey?.ciphertext, value.expiresAt]
166
+ ]);
167
+ let credentialGeneration = 0;
168
+ let credential = credentialIdentity(row);
147
169
  const install = (value) => {
148
170
  const next = JSON.stringify(value);
149
171
  const changed = fingerprint !== next;
150
172
  fingerprint = next;
151
- if (changed || state.status === "error") publish({ status: value?.status ?? "inactive" }, changed);
173
+ const nextCredential = credentialIdentity(value);
174
+ const renewed = nextCredential !== credential;
175
+ credential = nextCredential;
176
+ if (renewed) credentialGeneration++;
177
+ if (changed || state.status === "error") publish({ status: value?.status ?? "inactive" }, renewed);
152
178
  };
153
179
  const watch = backend.changes?.watch ?? backend.watchSubset?.({
154
180
  from: {
@@ -165,24 +191,19 @@ const makeServiceConnections = Effect.fn("Connect.connections")(function* (optio
165
191
  while: (error) => error.retryable
166
192
  }), Effect.catch((error) => Effect.logError("Connection watch stopped", error)), Effect.forkScoped({ startImmediately: true }));
167
193
  yield* read(ref.objectType, ref.id).pipe(Effect.tap((value) => Effect.sync(() => install(value))));
168
- const authentication = {
169
- get state() {
170
- return state;
171
- },
172
- changes: Stream.callback((queue) => Effect.acquireRelease(Effect.sync(() => {
173
- const send = (next) => {
174
- Queue.offerUnsafe(queue, next);
175
- };
176
- listeners.add(send);
177
- send(state);
178
- return send;
179
- }), (send) => Effect.sync(() => {
180
- listeners.delete(send);
181
- })), {
182
- bufferSize: 1,
183
- strategy: "sliding"
184
- })
185
- };
194
+ const monitor = { changes: Stream.callback((queue) => Effect.acquireRelease(Effect.sync(() => {
195
+ const send = (next) => {
196
+ Queue.offerUnsafe(queue, next);
197
+ };
198
+ listeners.add(send);
199
+ send(state);
200
+ return send;
201
+ }), (send) => Effect.sync(() => {
202
+ listeners.delete(send);
203
+ })), {
204
+ bufferSize: 1,
205
+ strategy: "sliding"
206
+ }) };
186
207
  const handlers = options.handlers ?? createDefaultConnectionEgressHandlers();
187
208
  const sockets = /* @__PURE__ */ new Set();
188
209
  const lifetime = new AbortController();
@@ -192,18 +213,6 @@ const makeServiceConnections = Effect.fn("Connect.connections")(function* (optio
192
213
  for (const socket of sockets) socket.close();
193
214
  sockets.clear();
194
215
  }));
195
- const refresh = yield* Semaphore.make(1);
196
- const refreshCredential = (rejected) => refresh.withPermit(Effect.gen(function* () {
197
- const current = yield* currentCredential();
198
- if (current !== rejected) return current;
199
- if (ref.objectType !== "OAuthConnection") return yield* unavailable("This connection requires authentication.");
200
- yield* backend.applyAction({
201
- id: crypto.randomUUID(),
202
- name: "refreshConnection",
203
- parameters: { connectionId: ref.id }
204
- });
205
- return yield* currentCredential();
206
- }));
207
216
  const acquired = yield* service.acquire({
208
217
  connection: {
209
218
  objectType: ref.objectType,
@@ -211,7 +220,6 @@ const makeServiceConnections = Effect.fn("Connect.connections")(function* (optio
211
220
  },
212
221
  serviceInstance,
213
222
  credential: currentCredential(),
214
- refreshCredential,
215
223
  handlers: {
216
224
  fetch: (request) => handlers.fetch(new Request(request, { signal: AbortSignal.any([request.signal, lifetime.signal]) })),
217
225
  createWebSocket: Effect.fnUntraced(function* (url, protocols) {
@@ -228,44 +236,98 @@ const makeServiceConnections = Effect.fn("Connect.connections")(function* (optio
228
236
  });
229
237
  const scope = yield* Effect.scope;
230
238
  const owned = (work) => Effect.suspend(() => scope.state._tag === "Closed" ? Effect.fail(unavailable("The selected connection was released.")) : Effect.acquireUseRelease(Effect.forkIn(work, scope), Fiber.join, Fiber.interrupt));
239
+ const markNeedsAuthentication = (observed) => options.store.transaction(Effect.gen(function* () {
240
+ const current = yield* options.store.get(ref.objectType, ref.id);
241
+ if (current?.status === "active" && credentialVersion(current) === observed) yield* options.store.put(ref.objectType, {
242
+ ...current,
243
+ status: "needs-auth"
244
+ });
245
+ })).pipe(Effect.mapError(connectBackendError), Effect.tapError((cause) => Effect.logError("Could not save connection authentication status", cause)), Effect.ignore, Effect.uninterruptible);
231
246
  const failed = Effect.fnUntraced(function* (error, observed) {
232
- if (isUnauthenticatedError(error)) yield* options.store.transaction(Effect.gen(function* () {
233
- const current = yield* options.store.get(ref.objectType, ref.id);
234
- if (current?.status === "active" && credentialVersion(current) === observed) yield* options.store.put(ref.objectType, {
235
- ...current,
236
- status: "needs-auth"
237
- });
238
- })).pipe(Effect.mapError(connectBackendError), Effect.tapError((cause) => Effect.logError("Could not save connection authentication status", cause)), Effect.ignore, Effect.uninterruptible);
247
+ if (isUnauthenticatedError(error)) yield* markNeedsAuthentication(observed);
239
248
  return yield* error;
240
249
  });
250
+ const renewal = yield* Semaphore.make(1);
251
+ let renewals = 0;
252
+ let failedRenewal;
253
+ const renew = (version) => Effect.suspend(() => {
254
+ const waitingSince = renewals;
255
+ return renewal.withPermit(Effect.gen(function* () {
256
+ if (version !== credentialGeneration) return;
257
+ if (failedRenewal?.version === version && failedRenewal.attempt > waitingSince) return yield* failedRenewal.error;
258
+ const current = yield* read(ref.objectType, ref.id);
259
+ if (current?.status !== "active") return;
260
+ if (ref.objectType !== "OAuthConnection") {
261
+ yield* markNeedsAuthentication(credentialVersion(current));
262
+ return;
263
+ }
264
+ const result = yield* Effect.result(backend.applyAction({
265
+ id: crypto.randomUUID(),
266
+ name: "refreshConnection",
267
+ parameters: { connectionId: ref.id }
268
+ }));
269
+ install(yield* read(ref.objectType, ref.id));
270
+ if (result._tag === "Failure" && !isUnauthenticatedError(result.failure)) {
271
+ const error = renewalUnavailable(result.failure);
272
+ failedRenewal = {
273
+ version,
274
+ attempt: ++renewals,
275
+ error
276
+ };
277
+ return yield* error;
278
+ }
279
+ renewals++;
280
+ }));
281
+ });
241
282
  const requireAuthentication = Effect.fnUntraced(function* () {
242
283
  const current = yield* read(ref.objectType, ref.id);
243
284
  if (!current || current.status === "inactive") return yield* unavailable("The selected connection is disconnected.");
244
285
  if (current.status !== "active") return yield* unavailable("The selected connection requires authentication.");
245
286
  return current;
246
287
  });
288
+ const egress = {
289
+ fetch: (input, init) => owned(Effect.gen(function* () {
290
+ const version = credentialGeneration;
291
+ let observed = credentialVersion(yield* requireAuthentication());
292
+ const request = yield* Effect.try({
293
+ try: () => new Request(input, init),
294
+ catch: (cause) => classifyBackendFailure("connect.egress.fetch", cause)
295
+ });
296
+ const replay = request.body === null ? request.clone() : void 0;
297
+ const send = (value) => acquired.fetch(value).pipe(Effect.provideService(CredentialObserver, (value) => {
298
+ observed = value;
299
+ }));
300
+ const first = yield* Effect.result(send(request));
301
+ if (first._tag === "Success") return first.success;
302
+ if (!isUnauthenticatedError(first.failure) || ref.objectType !== "OAuthConnection") return yield* failed(first.failure, observed);
303
+ yield* renew(version);
304
+ if (state.status !== "active") return yield* first.failure;
305
+ if (!replay) return yield* retryAfterRenewal();
306
+ observed = credentialVersion(yield* requireAuthentication());
307
+ return yield* send(replay).pipe(Effect.catch((error) => failed(error, observed)));
308
+ })),
309
+ createWebSocket: (url, protocols) => owned(Effect.gen(function* () {
310
+ let observed = credentialVersion(yield* requireAuthentication());
311
+ return yield* acquired.createWebSocket(url, protocols).pipe(Effect.provideService(CredentialObserver, (value) => {
312
+ observed = value;
313
+ }), Effect.catch((error) => failed(error, observed)));
314
+ }))
315
+ };
316
+ const authentication = {
317
+ get state() {
318
+ return state;
319
+ },
320
+ changes: monitor.changes,
321
+ get credentialVersion() {
322
+ return credentialGeneration;
323
+ },
324
+ refresh: renew
325
+ };
247
326
  return {
248
327
  connection: ref,
249
328
  userId: row.userId,
250
329
  serviceInstance,
251
- egress: {
252
- fetch: (input, init) => owned(Effect.gen(function* () {
253
- let observed = credentialVersion(yield* requireAuthentication());
254
- const request = yield* Effect.try({
255
- try: () => new Request(input, init),
256
- catch: (cause) => classifyBackendFailure("connect.egress.fetch", cause)
257
- });
258
- return yield* acquired.fetch(request).pipe(Effect.provideService(CredentialObserver, (value) => {
259
- observed = value;
260
- }), Effect.catch((error) => failed(error, observed)));
261
- })),
262
- createWebSocket: (url, protocols) => owned(Effect.gen(function* () {
263
- let observed = credentialVersion(yield* requireAuthentication());
264
- return yield* acquired.createWebSocket(url, protocols).pipe(Effect.provideService(CredentialObserver, (value) => {
265
- observed = value;
266
- }), Effect.catch((error) => failed(error, observed)));
267
- }))
268
- },
330
+ egress,
269
331
  authentication
270
332
  };
271
333
  }) });
@@ -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 ConnectionMonitor,\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 readonly authentication: ConnectionMonitor;\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);\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 const install = (value: typeof row | undefined) => {\n const next = JSON.stringify(value);\n const changed = fingerprint !== next;\n fingerprint = next;\n if (changed || state.status === \"error\")\n publish({ status: value?.status ?? \"inactive\" }, changed);\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 authentication: ConnectionMonitor = {\n get state() {\n return state;\n },\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 refresh = yield* Semaphore.make(1);\n const refreshCredential = (rejected: string) =>\n refresh.withPermit(\n Effect.gen(function* () {\n const current = yield* currentCredential();\n if (current !== rejected) return current;\n if (ref.objectType !== \"OAuthConnection\")\n return yield* unavailable(\"This connection requires authentication.\");\n yield* backend.applyAction({\n id: crypto.randomUUID(),\n name: \"refreshConnection\",\n parameters: { connectionId: ref.id },\n });\n return yield* currentCredential();\n })\n );\n const acquired = yield* service.acquire({\n connection: { objectType: ref.objectType, value: row } as SavedConnection,\n serviceInstance,\n credential: currentCredential(),\n refreshCredential,\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 const failed = Effect.fnUntraced(function* (error: BackendError, observed: string | undefined) {\n if (isUnauthenticatedError(error)) {\n // Compare and persist in one transaction: a late rejection must\n // neither pause a newer login nor resurrect a disconnected row.\n // The ordinary journal/watch path also updates account queries.\n yield* 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 )\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 }\n return yield* error;\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 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 return yield* acquired.fetch(request).pipe(\n Effect.provideService(CredentialObserver, (value) => {\n observed = value;\n }),\n Effect.catch((error) => failed(error, observed))\n );\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 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":";;;;;;;;;AA8BA,MAAM,eAAe,YACjB,IAAI,aAAa;CACb,WAAW;CACX,MA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OAAO,SAAS,gBAAgB,KAAK,SAAS,CAAC,CAAC,KACnD,OAAO,eAAe,qBAAqB,UAAU;MACjD,WAAW;KACf,CAAC,GACD,OAAO,OAAO,UAAU,OAAO,OAAO,QAAQ,CAAC,CACnD;IACJ,CAAC,CACL;GAMC;GACL;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 { 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,MAAa,yBAAyB,OAAO,GAAG,qBAAqB,CAAC,CAAC,WAAW,SAK/E;CACC,MAAM,UAAU,QAAQ;CACxB,MAAM,WAAW,IAAI,IAAI,QAAQ,SAAS,KAAK,YAAY,CAAC,QAAQ,SAAS,OAAO,CAAC,CAAC;CACtF,IAAI,SAAS,SAAS,QAAQ,SAAS,QACnC,OAAO,OAAO,IAAI,aAAa;EAC3B,WAAW;EACX,MAAM;EACN,WAAW;EACX,SAAS;CACb,CAAC;CACL,MAAM,OAAO,OAAO,WAAW,WAC3B,YACA,IACF;EAcE,QAAQ,OAbY,QAAQ,MAAM,EAC9B,QAAQ,CACJ,EAAE,IAAI,QAAQ;GACV,MAAM;IAAE,QAAQ,EAAE,WAAW;IAAG,SAAS;GAAM;GAC/C,OAAO,EAAE,GAAG,EAAE,MAAM,OAAO,IAAI,GAAG,EAAE,QAAQ,EAAE,CAAC;GAC/C,QAAQ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,CACL;IACJ,MAAM,QAAQ,OAAO,OAAO,OAAO,KAAK,OAAO,CAAC;IAChD,IAAI,MAAM,SAAS,WAAW,OAAO,MAAM;IAC3C,IACI,CAAC,uBAAuB,MAAM,OAAO,KACrC,IAAI,eAAe,mBAEnB,OAAO,OAAO,OAAO,MAAM,SAAS,QAAQ;IAChD,OAAO,MAAM,OAAO;IACpB,IAAI,MAAM,WAAW,UAAU,OAAO,OAAO,MAAM;IACnD,IAAI,CAAC,QAAQ,OAAO,OAAO,kBAAkB;IAC7C,WAAW,kBAAkB,OAAO,sBAAsB,CAAC;IAC3D,OAAO,OAAO,KAAK,MAAM,CAAC,CAAC,KAAK,OAAO,OAAO,UAAU,OAAO,OAAO,QAAQ,CAAC,CAAC;GACpF,CAAC,CACL;GACJ,kBAAkB,KAAK,cACnB,MACI,OAAO,IAAI,aAAa;IACpB,IAAI,WAAW,kBAAkB,OAAO,sBAAsB,CAAC;IAC/D,OAAO,OAAO,SAAS,gBAAgB,KAAK,SAAS,CAAC,CAAC,KACnD,OAAO,eAAe,qBAAqB,UAAU;KACjD,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"}
package/lib/types.d.ts CHANGED
@@ -40,5 +40,17 @@ export interface ConnectionMonitor {
40
40
  /** Includes the current state, followed by connection lifecycle changes. */
41
41
  readonly changes: Stream.Stream<ConnectionState>;
42
42
  }
43
+ /** What a replica that owns this connection's sync needs beyond the read-only monitor
44
+ * apps show: renewing a credential that was rejected after egress returned, such as
45
+ * a websocket the provider closes when its token expires. */
46
+ export interface ConnectionLifecycle extends ConnectionMonitor {
47
+ /** Changes whenever the saved credential changes, including a renewal. */
48
+ readonly credentialVersion: number;
49
+ /** Renew the credential that was current at `version`. Does nothing when a newer
50
+ * credential already replaced it. A renewal publishes a new active state; a
51
+ * credential that cannot be renewed moves the connection to `needs-auth`. Fails
52
+ * only for a retryable problem, such as the provider being unreachable. */
53
+ readonly refresh: (version: number) => Effect.Effect<void, BackendError>;
54
+ }
43
55
  //#endregion
44
56
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","names":[],"sources":["../src/types.ts"],"mappings":";;;qBAKa,uBAAqB,OAAA,gBAAA,OAAA;;;;;;;;;;;;;;;;;YAUtB,yBAAyB,sBAAsB;YAE/C,mBAAmB;iBAEd;EACb,MAAM,SAAS,UAAU,OAAO,OAAO,UAAU;EACjD,gBAAgB,cAAc,KAAK,gCAAgC,OAAO,OAAO,WAAW;;iBAG/E;EACb,MAAM,OAAO,cAAc,KAAK,OAAO,cAAc,OAAO,OAAO,UAAU;EAC7E,gBAAgB,cAAc,KAAK,gCAAgC,OAAO,OAAO,WAAW;;;iBAI/E,WAAW,eAAe,mBAAmB;EAC1D;EACA,OAAO;IAAoB,QAAQ;;;iBAGtB;WACJ,OAAO;;WAEP,SAAS,OAAO,OAAO"}
1
+ {"version":3,"file":"types.d.ts","names":[],"sources":["../src/types.ts"],"mappings":";;;qBAKa,uBAAqB,OAAA,gBAAA,OAAA;;;;;;;;;;;;;;;;;YAUtB,yBAAyB,sBAAsB;YAE/C,mBAAmB;iBAEd;EACb,MAAM,SAAS,UAAU,OAAO,OAAO,UAAU;EACjD,gBAAgB,cAAc,KAAK,gCAAgC,OAAO,OAAO,WAAW;;iBAG/E;EACb,MAAM,OAAO,cAAc,KAAK,OAAO,cAAc,OAAO,OAAO,UAAU;EAC7E,gBAAgB,cAAc,KAAK,gCAAgC,OAAO,OAAO,WAAW;;;iBAI/E,WAAW,eAAe,mBAAmB;EAC1D;EACA,OAAO;IAAoB,QAAQ;;;iBAGtB;WACJ,OAAO;;WAEP,SAAS,OAAO,OAAO;;;;;iBAMnB,4BAA4B;;WAEhC;;;;;WAKA,UAAU,oBAAoB,OAAO,aAAa"}
package/lib/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["import { Schema } from \"effect\";\nimport type { BackendError } from \"@party-stack/ontology-backend\";\nimport type { Stream } from \"effect\";\nimport type { Effect } from \"effect\";\n\nexport const ConnectionStateSchema = Schema.Union([\n Schema.Struct({ status: Schema.Literal(\"pending\") }),\n Schema.Struct({\n status: Schema.Literal(\"active\"),\n expiration: Schema.optional(Schema.Struct({ expiresAt: Schema.Number, refreshable: Schema.Boolean })),\n }),\n Schema.Struct({ status: Schema.Literal(\"inactive\") }),\n Schema.Struct({ status: Schema.Literal(\"needs-auth\"), error: Schema.optional(Schema.String) }),\n Schema.Struct({ status: Schema.Literal(\"error\"), error: Schema.String }),\n]);\nexport type ConnectionState = typeof ConnectionStateSchema.Type;\n\nexport type ConnectionStatus = ConnectionState[\"status\"];\n\nexport interface ConnectionEgressHandlers {\n fetch(request: Request): Effect.Effect<Response, BackendError>;\n createWebSocket(url: string | URL, protocols?: string | string[]): Effect.Effect<WebSocket, BackendError>;\n}\n\nexport interface ConnectionEgress {\n fetch(input: RequestInfo | URL, init?: RequestInit): Effect.Effect<Response, BackendError>;\n createWebSocket(url: string | URL, protocols?: string | string[]): Effect.Effect<WebSocket, BackendError>;\n}\n\n/** Serializable, reactive connection metadata and lifecycle state. */\nexport interface Connection<Status extends ConnectionStatus = ConnectionStatus> {\n userId: string;\n state: ConnectionState & { status: Status };\n}\n\nexport interface ConnectionMonitor {\n readonly state: ConnectionState;\n /** Includes the current state, followed by connection lifecycle changes. */\n readonly changes: Stream.Stream<ConnectionState>;\n}\n"],"mappings":";;AAKA,MAAa,wBAAwB,OAAO,MAAM;CAC9C,OAAO,OAAO,EAAE,QAAQ,OAAO,QAAQ,SAAS,EAAE,CAAC;CACnD,OAAO,OAAO;EACV,QAAQ,OAAO,QAAQ,QAAQ;EAC/B,YAAY,OAAO,SAAS,OAAO,OAAO;GAAE,WAAW,OAAO;GAAQ,aAAa,OAAO;EAAQ,CAAC,CAAC;CACxG,CAAC;CACD,OAAO,OAAO,EAAE,QAAQ,OAAO,QAAQ,UAAU,EAAE,CAAC;CACpD,OAAO,OAAO;EAAE,QAAQ,OAAO,QAAQ,YAAY;EAAG,OAAO,OAAO,SAAS,OAAO,MAAM;CAAE,CAAC;CAC7F,OAAO,OAAO;EAAE,QAAQ,OAAO,QAAQ,OAAO;EAAG,OAAO,OAAO;CAAO,CAAC;AAC3E,CAAC"}
1
+ {"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["import { Schema } from \"effect\";\nimport type { BackendError } from \"@party-stack/ontology-backend\";\nimport type { Stream } from \"effect\";\nimport type { Effect } from \"effect\";\n\nexport const ConnectionStateSchema = Schema.Union([\n Schema.Struct({ status: Schema.Literal(\"pending\") }),\n Schema.Struct({\n status: Schema.Literal(\"active\"),\n expiration: Schema.optional(Schema.Struct({ expiresAt: Schema.Number, refreshable: Schema.Boolean })),\n }),\n Schema.Struct({ status: Schema.Literal(\"inactive\") }),\n Schema.Struct({ status: Schema.Literal(\"needs-auth\"), error: Schema.optional(Schema.String) }),\n Schema.Struct({ status: Schema.Literal(\"error\"), error: Schema.String }),\n]);\nexport type ConnectionState = typeof ConnectionStateSchema.Type;\n\nexport type ConnectionStatus = ConnectionState[\"status\"];\n\nexport interface ConnectionEgressHandlers {\n fetch(request: Request): Effect.Effect<Response, BackendError>;\n createWebSocket(url: string | URL, protocols?: string | string[]): Effect.Effect<WebSocket, BackendError>;\n}\n\nexport interface ConnectionEgress {\n fetch(input: RequestInfo | URL, init?: RequestInit): Effect.Effect<Response, BackendError>;\n createWebSocket(url: string | URL, protocols?: string | string[]): Effect.Effect<WebSocket, BackendError>;\n}\n\n/** Serializable, reactive connection metadata and lifecycle state. */\nexport interface Connection<Status extends ConnectionStatus = ConnectionStatus> {\n userId: string;\n state: ConnectionState & { status: Status };\n}\n\nexport interface ConnectionMonitor {\n readonly state: ConnectionState;\n /** Includes the current state, followed by connection lifecycle changes. */\n readonly changes: Stream.Stream<ConnectionState>;\n}\n\n/** What a replica that owns this connection's sync needs beyond the read-only monitor\n * apps show: renewing a credential that was rejected after egress returned, such as\n * a websocket the provider closes when its token expires. */\nexport interface ConnectionLifecycle extends ConnectionMonitor {\n /** Changes whenever the saved credential changes, including a renewal. */\n readonly credentialVersion: number;\n /** Renew the credential that was current at `version`. Does nothing when a newer\n * credential already replaced it. A renewal publishes a new active state; a\n * credential that cannot be renewed moves the connection to `needs-auth`. Fails\n * only for a retryable problem, such as the provider being unreachable. */\n readonly refresh: (version: number) => Effect.Effect<void, BackendError>;\n}\n"],"mappings":";;AAKA,MAAa,wBAAwB,OAAO,MAAM;CAC9C,OAAO,OAAO,EAAE,QAAQ,OAAO,QAAQ,SAAS,EAAE,CAAC;CACnD,OAAO,OAAO;EACV,QAAQ,OAAO,QAAQ,QAAQ;EAC/B,YAAY,OAAO,SAAS,OAAO,OAAO;GAAE,WAAW,OAAO;GAAQ,aAAa,OAAO;EAAQ,CAAC,CAAC;CACxG,CAAC;CACD,OAAO,OAAO,EAAE,QAAQ,OAAO,QAAQ,UAAU,EAAE,CAAC;CACpD,OAAO,OAAO;EAAE,QAAQ,OAAO,QAAQ,YAAY;EAAG,OAAO,OAAO,SAAS,OAAO,MAAM;CAAE,CAAC;CAC7F,OAAO,OAAO;EAAE,QAAQ,OAAO,QAAQ,OAAO;EAAG,OAAO,OAAO;CAAO,CAAC;AAC3E,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@party-stack/connect",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "files": [
5
5
  "lib"
6
6
  ],
@@ -23,10 +23,10 @@
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.2.1",
27
- "@party-stack/ontology-spec": "0.3.0",
28
- "@party-stack/ontology-storage": "0.2.1",
29
- "@party-stack/runtime": "0.5.1"
26
+ "@party-stack/ontology-backend": "0.2.2",
27
+ "@party-stack/ontology-spec": "0.3.1",
28
+ "@party-stack/ontology-storage": "0.2.2",
29
+ "@party-stack/runtime": "0.6.0"
30
30
  },
31
31
  "devDependencies": {
32
32
  "typescript": "~7.0.2",