@party-stack/connect 0.0.0-stage → 0.2.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.
Files changed (96) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +189 -2
  3. package/lib/ServiceConnector.d.ts +68 -0
  4. package/lib/ServiceConnector.d.ts.map +1 -0
  5. package/lib/ServiceConnector.js +1 -0
  6. package/lib/acquireConfiguredConnection.d.ts +32 -0
  7. package/lib/acquireConfiguredConnection.d.ts.map +1 -0
  8. package/lib/acquireConfiguredConnection.js +54 -0
  9. package/lib/acquireConfiguredConnection.js.map +1 -0
  10. package/lib/authentication.d.ts +76 -0
  11. package/lib/authentication.d.ts.map +1 -0
  12. package/lib/authentication.js +95 -0
  13. package/lib/authentication.js.map +1 -0
  14. package/lib/authorization.d.ts +43 -0
  15. package/lib/authorization.d.ts.map +1 -0
  16. package/lib/authorization.js +175 -0
  17. package/lib/authorization.js.map +1 -0
  18. package/lib/core/accessToken.d.ts +10 -0
  19. package/lib/core/accessToken.d.ts.map +1 -0
  20. package/lib/core/accessToken.js +87 -0
  21. package/lib/core/accessToken.js.map +1 -0
  22. package/lib/core/backend.d.ts +33 -0
  23. package/lib/core/backend.d.ts.map +1 -0
  24. package/lib/core/backend.js +249 -0
  25. package/lib/core/backend.js.map +1 -0
  26. package/lib/core/errors.d.ts +13 -0
  27. package/lib/core/errors.d.ts.map +1 -0
  28. package/lib/core/errors.js +26 -0
  29. package/lib/core/errors.js.map +1 -0
  30. package/lib/core/maintenance.d.ts +11 -0
  31. package/lib/core/maintenance.d.ts.map +1 -0
  32. package/lib/core/maintenance.js +21 -0
  33. package/lib/core/maintenance.js.map +1 -0
  34. package/lib/core/migrate.d.ts +18 -0
  35. package/lib/core/migrate.d.ts.map +1 -0
  36. package/lib/core/migrate.js +71 -0
  37. package/lib/core/migrate.js.map +1 -0
  38. package/lib/core/oauth.d.ts +27 -0
  39. package/lib/core/oauth.d.ts.map +1 -0
  40. package/lib/core/oauth.js +82 -0
  41. package/lib/core/oauth.js.map +1 -0
  42. package/lib/core/oauthAuthority.d.ts +90 -0
  43. package/lib/core/oauthAuthority.d.ts.map +1 -0
  44. package/lib/core/oauthAuthority.js +382 -0
  45. package/lib/core/oauthAuthority.js.map +1 -0
  46. package/lib/core/store.d.ts +48 -0
  47. package/lib/core/store.d.ts.map +1 -0
  48. package/lib/core/store.js +92 -0
  49. package/lib/core/store.js.map +1 -0
  50. package/lib/createDefaultConnectionEgressHandlers.d.ts +5 -0
  51. package/lib/createDefaultConnectionEgressHandlers.d.ts.map +1 -0
  52. package/lib/createDefaultConnectionEgressHandlers.js +20 -0
  53. package/lib/createDefaultConnectionEgressHandlers.js.map +1 -0
  54. package/lib/index.d.ts +20 -0
  55. package/lib/index.js +17 -0
  56. package/lib/makeConnectManager.d.ts +90 -0
  57. package/lib/makeConnectManager.d.ts.map +1 -0
  58. package/lib/makeConnectManager.js +91 -0
  59. package/lib/makeConnectManager.js.map +1 -0
  60. package/lib/oauth/storage.d.ts +9 -0
  61. package/lib/oauth/storage.d.ts.map +1 -0
  62. package/lib/oauth/storage.js +16 -0
  63. package/lib/oauth/storage.js.map +1 -0
  64. package/lib/publicOntology.d.ts +17 -0
  65. package/lib/publicOntology.d.ts.map +1 -0
  66. package/lib/publicOntology.js +86 -0
  67. package/lib/publicOntology.js.map +1 -0
  68. package/lib/server/index.d.ts +33 -0
  69. package/lib/server/index.d.ts.map +1 -0
  70. package/lib/server/index.js +119 -0
  71. package/lib/server/index.js.map +1 -0
  72. package/lib/serverClient.d.ts +28 -0
  73. package/lib/serverClient.d.ts.map +1 -0
  74. package/lib/serverClient.js +67 -0
  75. package/lib/serverClient.js.map +1 -0
  76. package/lib/serviceConnections.d.ts +39 -0
  77. package/lib/serviceConnections.d.ts.map +1 -0
  78. package/lib/serviceConnections.js +277 -0
  79. package/lib/serviceConnections.js.map +1 -0
  80. package/lib/spec/index.d.ts +958 -0
  81. package/lib/spec/index.d.ts.map +1 -0
  82. package/lib/spec/index.js +565 -0
  83. package/lib/spec/index.js.map +1 -0
  84. package/lib/toWebEgress.d.ts +12 -0
  85. package/lib/toWebEgress.d.ts.map +1 -0
  86. package/lib/toWebEgress.js +28 -0
  87. package/lib/toWebEgress.js.map +1 -0
  88. package/lib/types.d.ts +44 -0
  89. package/lib/types.d.ts.map +1 -0
  90. package/lib/types.js +25 -0
  91. package/lib/types.js.map +1 -0
  92. package/lib/withHttpAuthenticationErrors.d.ts +5 -0
  93. package/lib/withHttpAuthenticationErrors.d.ts.map +1 -0
  94. package/lib/withHttpAuthenticationErrors.js +20 -0
  95. package/lib/withHttpAuthenticationErrors.js.map +1 -0
  96. package/package.json +34 -3
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Robert Fidler
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,190 @@
1
- # Temporary Holding Version
1
+ # Connect
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Connect’s role is saving connections and turning them into authenticated access.**
4
+ It stores service instances and saved connections as ontology objects. A
5
+ native owner acquires authenticated access from a connection, then passes that
6
+ access to an ordinary backend constructor. The same backend can be exposed over
7
+ HTTP or a worker port using the ontology server.
8
+
9
+ - **Service** identifies an integration such as Foundry or Better Auth.
10
+ - **ServiceInstance** identifies its configured deployment.
11
+ - **ServiceConnector** is the native integration for OAuth, API keys or external sessions, and authenticated egress.
12
+ - **OAuthApplication** stores a registered client configuration.
13
+ - **OAuthConnection**, **ApiKeyConnection** and **ExternalSessionConnection** store concrete saved connections. Token/key properties are encrypted at the top level; an external session stores a selector that its service must verify.
14
+ - **OAuthAuthorizationAttempt** stores the single-use PKCE workflow.
15
+
16
+ `@party-stack/connect/spec` exports the portable IR and inferred record types.
17
+ Applications can extend its definitions and policy. There is no mandatory user or
18
+ ACL schema in the core ontology.
19
+
20
+ ## Native owner
21
+
22
+ `makeConnectManager` requires an Effect `Runtime` and `Scope`. Runtime supplies Tables and
23
+ encryption keys; a persistent browser runtime must opt into persistent key storage.
24
+ `ConnectManager.layer(options)` provides the same service through an Effect Layer.
25
+
26
+ ```ts
27
+ const connect =
28
+ yield *
29
+ makeConnectManager({
30
+ services: [
31
+ {
32
+ connector: makeFoundryServiceConnector(),
33
+ instances: [
34
+ {
35
+ id: "foundry",
36
+ instanceUrl: "https://example.palantirfoundry.com",
37
+ OAuthApplications: [
38
+ {
39
+ id: "app",
40
+ clientId,
41
+ redirectUrl,
42
+ scopes: ["api:use-ontologies-read", "offline_access"],
43
+ },
44
+ ],
45
+ },
46
+ ],
47
+ },
48
+ ],
49
+ });
50
+
51
+ const access = yield * connect.connections.acquire({ objectType: "OAuthConnection", id: connectionId });
52
+ const backend =
53
+ yield *
54
+ makeFoundryBackend({
55
+ baseUrl: access.serviceInstance.instanceUrl,
56
+ ontologyId,
57
+ ir,
58
+ context: { userId: access.userId },
59
+ egress: access.egress,
60
+ });
61
+ ```
62
+
63
+ The manager holds scoped authenticated I/O, watches credential changes and
64
+ releases sockets/requests when their owner closes. Each outgoing request uses the
65
+ current credential. A response using old credentials cannot pause a newer login.
66
+ It does not persist a second connection inventory.
67
+
68
+ Only an instance URL and each OAuth application's client configuration are required.
69
+ Instance IDs default to a stable service + canonical URL key; application IDs default
70
+ to instance ID + client ID. Titles default to the connector's display name, and flow
71
+ defaults to `authorization-code`. Explicit IDs/titles/flow override those defaults.
72
+ The example keeps `app` as an explicit ID because its tab sign-in helper selects it.
73
+ Changing titles or reordering configuration does not change derived identities.
74
+
75
+ `OAuthApplications` contains per-application `scopes`. If omitted, the manager uses
76
+ the connector's `defaultOAuthScopes`; an explicit empty array requests no scopes.
77
+ Resolved configuration is persisted as ordinary ServiceInstance/OAuthApplication
78
+ records and exposed through the inventory policy without client secrets.
79
+
80
+ CLI/provider bootstrap can use `acquireConfiguredConnection({ manager,
81
+ serviceInstanceId, oauth, userId, browserAuthentication })`. It reuses a saved
82
+ account or runs the configured OAuth flow, then calls the same
83
+ `manager.connections.acquire`. API-key bootstrap supplies `apiKey` instead of
84
+ `oauth`. No separate CLI connection manager or credential inventory is created.
85
+
86
+ `makeAuthenticationClient({ backend, browserAuthentication })` provides Effect-native
87
+ commands and inventory queries. `createAuthenticationClient` is its Promise SDK facade.
88
+
89
+ `makeConnectBackend` is the lower-level constructor for owners supplying Tables
90
+ and encrypted values directly. Its `store` is trusted native persistence;
91
+ `backend` is the ordinary read/action interface.
92
+
93
+ ## Serve and use it
94
+
95
+ Mount `connect.backend` as a named ontology on the normal ontology server. For
96
+ trusted local tabs, `connectPublicOntologyIR` allows inventory reads and explicit
97
+ authentication actions while excluding token properties and PKCE attempts.
98
+ Network servers must also scope that policy to their authenticated callers.
99
+
100
+ Select `"connect"` through `httpClient` or `workerClient`. No separate installation
101
+ protocol or authentication-method proxy is needed. Browser SDK commands live in
102
+ `@party-stack/ontology/authentication`:
103
+
104
+ ```ts
105
+ const authentication = await createAuthenticationClient({
106
+ client: workerClient(spawn, { ontology: "connect" }),
107
+ runtime,
108
+ });
109
+ const oauth = authentication.oauth({ applicationId: "app", redirectUrl });
110
+ const signedIn = await oauth.signIn({ browserPresentation: "popup" });
111
+ const saved = await authentication.connections();
112
+ await authentication.signOut(signedIn);
113
+ await authentication.forget(signedIn);
114
+ ```
115
+
116
+ The popup remains in the tab. `beginAuthorization` persists PKCE state;
117
+ `completeAuthorization` claims the attempt, performs the remote exchange, then
118
+ commits encrypted credentials. It checks state, callback location, expiry and
119
+ single-use consumption. An optional trusted `principalId` binds a server-hosted
120
+ attempt to its initiating caller. These workflow actions execute directly rather
121
+ than through an optimistic outbox.
122
+
123
+ Better Auth sign-in uses its normal tab SDK. `attachExternalSession` asks the
124
+ registered service connector to verify the actual session before saving its
125
+ selector. The resulting connection acquires a normal backend in the same way as
126
+ an OAuth connection. Neither variant requires forwarding a generic SDK over RPC.
127
+
128
+ Read inventory reactively using the ordinary Connect ontology and the
129
+ `authenticationObjects` descriptors from `@party-stack/ontology/authentication`.
130
+
131
+ ## Maintenance and local data
132
+
133
+ The manager starts scoped periodic maintenance by default. Set
134
+ `startMaintenance: false` when an external owner calls `manager.maintenance.run`,
135
+ such as a Durable Object alarm. Configure the interval with `maintenance.intervalMs`. Sweeps expire PKCE attempts, refresh secrets and connection expiry state,
136
+ and collect the owned journal/delivery metadata.
137
+
138
+ `authentication.signOut(account)` invokes the ordinary Connect disconnect actions;
139
+ `authentication.forget(account)` removes the saved row as well. Both use
140
+ `AccountRef`: `{ kind: "oauth" | "api-key" | "external-session", id }`. Sign-in and
141
+ inventory results include this shape. Native backend acquisition retains
142
+ `ConnectionRef` with `{ objectType, id }`.
143
+
144
+ Signing out detaches credentials and attempts remote revocation. Forgetting also
145
+ clears the account's OAuth attempts and application reference. Revocation failure
146
+ is reported after the local change commits and cannot restore credentials. Neither operation will
147
+ delete the application's cached objects or pending actions. Managed replica routes on `makeOntologyServer` keep a persisted partition inventory
148
+ so `server.forget(name)` works after credentials expire.
149
+
150
+ For a private SharedWorker, `connectDeviceRoute(manager)` returns its route binding:
151
+
152
+ ```ts
153
+ const server =
154
+ yield *
155
+ makeOntologyServer({
156
+ enableRealtime: true,
157
+ routes: { connect: connectDeviceRoute(manager) },
158
+ });
159
+ ```
160
+
161
+ This convenience uses `connectPublicOntologyIR`, the device-local inventory policy.
162
+ It does not isolate accounts between network callers. Public Connect deployments
163
+ must supply their own authenticated context and caller-specific policy.
164
+ Forget actions retain typed object-reference parameters and their normal
165
+ existence/visibility checks. Connect's current workflow executor does not provide
166
+ durable invocation receipts; a new command after account deletion can fail
167
+ reference validation. Account queries still reflect committed local deletion if
168
+ the command's reply is lost.
169
+
170
+ ## OAuth workflow transactions
171
+
172
+ Authentication uses a regular backend `applyAction` implementation that dispatches
173
+ workflow commands. OAuth completion validates and claims its saved attempt in a
174
+ transaction, exchanges the code outside the transaction, then commits encrypted credentials in a second transaction. Refresh uses the
175
+ same claim/request/commit pattern. The remote exchange cannot be rolled back with
176
+ local storage.
177
+
178
+ These workflows use normal owned persistence, but do not implement the native
179
+ owned mutator's transaction-level authorization hook. Serve this generic backend
180
+ with `kind: "proxy"` and a policy; the name describes its server interface, not a
181
+ remote deployment. Policy checks happen before workflow execution. A public
182
+ server must bind ownership/principal rules in addition to the device-local policy.
183
+ Durable claims are not a general action-result/idempotency system, so these
184
+ commands bypass the replica outbox and ordinary automatic action replay.
185
+
186
+ This generic backend is temporary. A future owned implementation should use
187
+ first-class durable workflows with persisted steps, separate transactions,
188
+ configurable retries and compensations. No staged `prepare` hook is required for
189
+ the current proxy path. Its storage commits already publish ordinary journal/watch
190
+ notifications, independently of whether a command reply reaches the caller.
@@ -0,0 +1,68 @@
1
+ import { ConnectError } from "./core/errors.js";
2
+ import { ApiKeyConnectionRecord, ExternalSessionConnectionRecord, OAuthApplicationRecord, OAuthConnectionRecord, ServiceInstanceRecord } from "./spec/index.js";
3
+ import { ConnectCredentialValues, ConnectOAuthService } from "./core/oauthAuthority.js";
4
+ import { ConnectionEgressHandlers } from "./types.js";
5
+ import { BackendError } from "@party-stack/ontology-backend";
6
+ import { Effect, Scope } from "effect";
7
+ import { Temporal } from "temporal-polyfill";
8
+ //#region src/ServiceConnector.d.ts
9
+ /** Concrete rows keep secrets in top-level encrypted properties. No runtime
10
+ * polymorphism is required in the ontology or in a service's storage adapter.
11
+ */
12
+ export type SavedConnection = {
13
+ readonly objectType: "OAuthConnection";
14
+ readonly value: OAuthConnectionRecord;
15
+ } | {
16
+ readonly objectType: "ApiKeyConnection";
17
+ readonly value: ApiKeyConnectionRecord;
18
+ } | {
19
+ readonly objectType: "ExternalSessionConnection";
20
+ readonly value: ExternalSessionConnectionRecord;
21
+ };
22
+ export type ConnectionRef = {
23
+ readonly objectType: SavedConnection["objectType"];
24
+ readonly id: string;
25
+ };
26
+ export interface VerifiedServiceIdentity {
27
+ readonly userId: string;
28
+ readonly title?: string;
29
+ readonly expiresAt?: Temporal.Instant;
30
+ }
31
+ /** Executable integration for a ServiceInstance. This is registered beside the
32
+ * credential owner. UI sign-in helpers operate over Connect's ordinary actions.
33
+ */
34
+ export interface ServiceConnector {
35
+ readonly service: string;
36
+ readonly displayName?: string;
37
+ readonly defaultOAuthScopes?: readonly string[];
38
+ readonly oauth?: (input: {
39
+ readonly application: OAuthApplicationRecord;
40
+ readonly serviceInstance: ServiceInstanceRecord;
41
+ readonly values: ConnectCredentialValues;
42
+ }) => Effect.Effect<ConnectOAuthService, ConnectError>;
43
+ readonly apiKey?: (input: {
44
+ readonly serviceInstance: ServiceInstanceRecord;
45
+ readonly apiKey: string;
46
+ }) => Effect.Effect<VerifiedServiceIdentity, ConnectError>;
47
+ readonly externalSession?: (input: {
48
+ readonly serviceInstance: ServiceInstanceRecord;
49
+ readonly sessionId: string;
50
+ }) => Effect.Effect<VerifiedServiceIdentity, ConnectError>;
51
+ readonly disconnectExternalSession?: (input: {
52
+ readonly serviceInstance: ServiceInstanceRecord;
53
+ readonly sessionId: string;
54
+ }) => Effect.Effect<void, ConnectError>;
55
+ readonly acquire: (input: {
56
+ readonly connection: SavedConnection;
57
+ readonly serviceInstance: ServiceInstanceRecord;
58
+ /** Rechecks and decrypts the saved credential; OAuth refresh is coordinated by Connect. */
59
+ 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
+ readonly handlers: ConnectionEgressHandlers;
65
+ }) => Effect.Effect<ConnectionEgressHandlers, BackendError, Scope.Scope>;
66
+ }
67
+ //#endregion
68
+ //# sourceMappingURL=ServiceConnector.d.ts.map
@@ -0,0 +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"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,32 @@
1
+ import { ServiceInstanceRecord } from "./spec/index.js";
2
+ import { ConnectionEgress, ConnectionMonitor } from "./types.js";
3
+ import { ConnectManagerService } from "./makeConnectManager.js";
4
+ import { BackendError } from "@party-stack/ontology-backend";
5
+ import { Effect } from "effect";
6
+ import { BrowserAuthentication } from "@party-stack/runtime";
7
+ //#region src/acquireConfiguredConnection.d.ts
8
+ /** CLI/bootstrap selection: reuse a saved account or execute the explicitly
9
+ * configured authentication flow. All credentials and I/O belong to manager.
10
+ */
11
+ export declare const acquireConfiguredConnection: (options: {
12
+ readonly manager: ConnectManagerService;
13
+ readonly serviceInstanceId: string;
14
+ readonly oauth?: {
15
+ readonly applicationId: string;
16
+ readonly redirectUrl: string;
17
+ };
18
+ readonly apiKey?: string;
19
+ readonly userId?: string;
20
+ readonly browserAuthentication?: BrowserAuthentication;
21
+ }) => Effect.Effect<{
22
+ connection: {
23
+ readonly objectType: "ApiKeyConnection" | "ExternalSessionConnection" | "OAuthConnection";
24
+ readonly id: string;
25
+ };
26
+ userId: string;
27
+ serviceInstance: ServiceInstanceRecord;
28
+ egress: ConnectionEgress;
29
+ authentication: ConnectionMonitor;
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
+ //#endregion
32
+ //# sourceMappingURL=acquireConfiguredConnection.d.ts.map
@@ -0,0 +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"}
@@ -0,0 +1,54 @@
1
+ import { makeAuthenticationClient } from "./authentication.js";
2
+ import { connectBackendError } from "./core/backend.js";
3
+ import { BackendError } from "@party-stack/ontology-backend";
4
+ import { eq, field } from "@party-stack/ontology-storage";
5
+ import { Effect } from "effect";
6
+ //#region src/acquireConfiguredConnection.ts
7
+ /** CLI/bootstrap selection: reuse a saved account or execute the explicitly
8
+ * configured authentication flow. All credentials and I/O belong to manager.
9
+ */
10
+ const acquireConfiguredConnection = Effect.fn("Connect.acquireConfiguredConnection")(function* (options) {
11
+ const { manager } = options;
12
+ const client = makeAuthenticationClient({
13
+ backend: manager.backend,
14
+ browserAuthentication: options.browserAuthentication
15
+ });
16
+ const invalid = (message) => new BackendError({
17
+ operation: "connect.select",
18
+ kind: "InvalidConfiguration",
19
+ retryable: false,
20
+ message
21
+ });
22
+ let selected;
23
+ if (options.apiKey) selected = {
24
+ objectType: "ApiKeyConnection",
25
+ id: (yield* client.connectApiKey(options.serviceInstanceId, options.apiKey)).id
26
+ };
27
+ else {
28
+ const type = options.oauth ? "OAuthConnection" : "ApiKeyConnection";
29
+ const rows = yield* manager.store.load(type, { where: options.oauth ? eq(field("application"), options.oauth.applicationId) : eq(field("serviceInstance"), options.serviceInstanceId) }).pipe(Effect.mapError(connectBackendError));
30
+ const active = rows.filter((row) => row.status === "active");
31
+ if (!options.userId && active.length > 1) return yield* invalid("Multiple accounts are signed in. Set connection.userId in the pull configuration.");
32
+ const existing = options.userId ? active.find((row) => row.userId === options.userId) : active[0];
33
+ if (existing) selected = {
34
+ objectType: type,
35
+ id: existing.id
36
+ };
37
+ else if (options.oauth) {
38
+ const previous = options.userId ? rows.find((row) => row.userId === options.userId) : void 0;
39
+ selected = {
40
+ objectType: "OAuthConnection",
41
+ id: (yield* client.oauth(options.oauth).signIn({ connectionId: previous?.id })).id
42
+ };
43
+ }
44
+ }
45
+ if (!selected) return yield* invalid("Configure OAuth or an API token, or select a saved account.");
46
+ const access = yield* manager.connections.acquire(selected);
47
+ if (access.serviceInstance.id !== options.serviceInstanceId) return yield* invalid("The selected connection belongs to a different service instance.");
48
+ if (options.userId && access.userId !== options.userId) return yield* invalid(`Authenticated as "${access.userId}", but connection.userId is "${options.userId}".`);
49
+ return access;
50
+ });
51
+ //#endregion
52
+ export { acquireConfiguredConnection };
53
+
54
+ //# sourceMappingURL=acquireConfiguredConnection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"acquireConfiguredConnection.js","names":[],"sources":["../src/acquireConfiguredConnection.ts"],"sourcesContent":["import { BackendError } from \"@party-stack/ontology-backend\";\nimport { eq, field } from \"@party-stack/ontology-storage\";\nimport { Effect } from \"effect\";\nimport { makeAuthenticationClient } from \"./authentication.js\";\nimport { connectBackendError } from \"./core/backend.js\";\nimport type { ConnectManagerService } from \"./makeConnectManager.js\";\nimport type { ConnectionRef } from \"./ServiceConnector.js\";\nimport type { BrowserAuthentication } from \"@party-stack/runtime\";\n\n/** CLI/bootstrap selection: reuse a saved account or execute the explicitly\n * configured authentication flow. All credentials and I/O belong to manager.\n */\nexport const acquireConfiguredConnection = Effect.fn(\"Connect.acquireConfiguredConnection\")(\n function* (options: {\n readonly manager: ConnectManagerService;\n readonly serviceInstanceId: string;\n readonly oauth?: { readonly applicationId: string; readonly redirectUrl: string };\n readonly apiKey?: string;\n readonly userId?: string;\n readonly browserAuthentication?: BrowserAuthentication;\n }) {\n const { manager } = options;\n const client = makeAuthenticationClient({\n backend: manager.backend,\n browserAuthentication: options.browserAuthentication,\n });\n const invalid = (message: string) =>\n new BackendError({\n operation: \"connect.select\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message,\n });\n let selected: ConnectionRef | undefined;\n if (options.apiKey) {\n const account = yield* client.connectApiKey(options.serviceInstanceId, options.apiKey);\n selected = { objectType: \"ApiKeyConnection\", id: account.id };\n } else {\n const type = options.oauth ? \"OAuthConnection\" : \"ApiKeyConnection\";\n const rows = yield* manager.store\n .load(type, {\n where: options.oauth\n ? eq(field(\"application\"), options.oauth.applicationId)\n : eq(field(\"serviceInstance\"), options.serviceInstanceId),\n })\n .pipe(Effect.mapError(connectBackendError));\n const active = rows.filter((row) => row.status === \"active\");\n if (!options.userId && active.length > 1)\n return yield* invalid(\n \"Multiple accounts are signed in. Set connection.userId in the pull configuration.\"\n );\n const existing = options.userId ? active.find((row) => row.userId === options.userId) : active[0];\n if (existing) selected = { objectType: type, id: existing.id };\n else if (options.oauth) {\n const previous = options.userId\n ? rows.find((row) => row.userId === options.userId)\n : undefined;\n const signedIn = yield* client.oauth(options.oauth).signIn({ connectionId: previous?.id });\n selected = { objectType: \"OAuthConnection\", id: signedIn.id };\n }\n }\n if (!selected) return yield* invalid(\"Configure OAuth or an API token, or select a saved account.\");\n const access = yield* manager.connections.acquire(selected);\n if (access.serviceInstance.id !== options.serviceInstanceId)\n return yield* invalid(\"The selected connection belongs to a different service instance.\");\n if (options.userId && access.userId !== options.userId)\n return yield* invalid(\n `Authenticated as \"${access.userId}\", but connection.userId is \"${options.userId}\".`\n );\n return access;\n }\n);\n"],"mappings":";;;;;;;;;AAYA,MAAa,8BAA8B,OAAO,GAAG,qCAAqC,CAAC,CACvF,WAAW,SAOR;CACC,MAAM,EAAE,YAAY;CACpB,MAAM,SAAS,yBAAyB;EACpC,SAAS,QAAQ;EACjB,uBAAuB,QAAQ;CACnC,CAAC;CACD,MAAM,WAAW,YACb,IAAI,aAAa;EACb,WAAW;EACX,MAAM;EACN,WAAW;EACX;CACJ,CAAC;CACL,IAAI;CACJ,IAAI,QAAQ,QAER,WAAW;EAAE,YAAY;EAAoB,KAAI,OAD1B,OAAO,cAAc,QAAQ,mBAAmB,QAAQ,MAAM,EAAA,CAC5B;CAAG;MACzD;EACH,MAAM,OAAO,QAAQ,QAAQ,oBAAoB;EACjD,MAAM,OAAO,OAAO,QAAQ,MACvB,KAAK,MAAM,EACR,OAAO,QAAQ,QACT,GAAG,MAAM,aAAa,GAAG,QAAQ,MAAM,aAAa,IACpD,GAAG,MAAM,iBAAiB,GAAG,QAAQ,iBAAiB,EAChE,CAAC,CAAC,CACD,KAAK,OAAO,SAAS,mBAAmB,CAAC;EAC9C,MAAM,SAAS,KAAK,QAAQ,QAAQ,IAAI,WAAW,QAAQ;EAC3D,IAAI,CAAC,QAAQ,UAAU,OAAO,SAAS,GACnC,OAAO,OAAO,QACV,mFACJ;EACJ,MAAM,WAAW,QAAQ,SAAS,OAAO,MAAM,QAAQ,IAAI,WAAW,QAAQ,MAAM,IAAI,OAAO;EAC/F,IAAI,UAAU,WAAW;GAAE,YAAY;GAAM,IAAI,SAAS;EAAG;OACxD,IAAI,QAAQ,OAAO;GACpB,MAAM,WAAW,QAAQ,SACnB,KAAK,MAAM,QAAQ,IAAI,WAAW,QAAQ,MAAM,IAChD,KAAA;GAEN,WAAW;IAAE,YAAY;IAAmB,KAAI,OADxB,OAAO,MAAM,QAAQ,KAAK,CAAC,CAAC,OAAO,EAAE,cAAc,UAAU,GAAG,CAAC,EAAA,CAChC;GAAG;EAChE;CACJ;CACA,IAAI,CAAC,UAAU,OAAO,OAAO,QAAQ,6DAA6D;CAClG,MAAM,SAAS,OAAO,QAAQ,YAAY,QAAQ,QAAQ;CAC1D,IAAI,OAAO,gBAAgB,OAAO,QAAQ,mBACtC,OAAO,OAAO,QAAQ,kEAAkE;CAC5F,IAAI,QAAQ,UAAU,OAAO,WAAW,QAAQ,QAC5C,OAAO,OAAO,QACV,qBAAqB,OAAO,OAAO,+BAA+B,QAAQ,OAAO,GACrF;CACJ,OAAO;AACX,CACJ"}
@@ -0,0 +1,76 @@
1
+ import { Connection } from "./types.js";
2
+ import { BackendError, OntologyBackendService } from "@party-stack/ontology-backend";
3
+ import { Effect } from "effect";
4
+ import { BrowserAuthentication } from "@party-stack/runtime";
5
+ //#region src/authentication.d.ts
6
+ export type AccountRef = {
7
+ readonly kind: "oauth" | "api-key" | "external-session";
8
+ readonly id: string;
9
+ };
10
+ export interface AccountSummary extends AccountRef {
11
+ readonly userId?: string;
12
+ readonly title: string;
13
+ readonly status: "active" | "needs-auth" | "inactive";
14
+ }
15
+ /** Effect-native commands and inventory queries over an ordinary Connect backend.
16
+ * Authentication actions execute directly; callers own the backend's Scope.
17
+ */
18
+ export declare function makeAuthenticationClient(options: {
19
+ readonly backend: OntologyBackendService;
20
+ readonly browserAuthentication?: BrowserAuthentication;
21
+ }): {
22
+ oauth: (settings: {
23
+ readonly applicationId: string;
24
+ readonly redirectUrl: string;
25
+ }) => {
26
+ redirectUrl: string;
27
+ signIn: (input?: Parameters<(options?: {
28
+ browserPresentation?: import("@party-stack/runtime").BrowserAuthenticationPresentation;
29
+ connectionId?: string;
30
+ }) => Effect.Effect<Connection<"active"> & {
31
+ readonly id: string;
32
+ }, BackendError>>[0]) => Effect.Effect<{
33
+ userId: string;
34
+ state: {
35
+ readonly status: "active";
36
+ readonly expiration?: {
37
+ readonly expiresAt: number;
38
+ readonly refreshable: boolean;
39
+ } | undefined;
40
+ } & {
41
+ status: "active";
42
+ };
43
+ id: string;
44
+ kind: "oauth";
45
+ }, BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, never>;
46
+ complete: (url: string) => Effect.Effect<{
47
+ userId: string;
48
+ state: {
49
+ readonly status: "active";
50
+ readonly expiration?: {
51
+ readonly expiresAt: number;
52
+ readonly refreshable: boolean;
53
+ } | undefined;
54
+ } & {
55
+ status: "active";
56
+ };
57
+ id: string;
58
+ kind: "oauth";
59
+ } | undefined, BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, never>;
60
+ };
61
+ attachExternalSession: (serviceInstanceId: string, sessionId: string) => Effect.Effect<{
62
+ kind: "external-session";
63
+ id: string;
64
+ }, BackendError<"InvalidResponse"> | BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, never>;
65
+ connectApiKey: (serviceInstanceId: string, apiKey: string) => Effect.Effect<{
66
+ kind: "api-key";
67
+ id: string;
68
+ }, BackendError<"InvalidResponse"> | BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, never>;
69
+ signOut: (account: AccountRef) => Effect.Effect<void, BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, never>;
70
+ /** Remove a saved account. Downloaded application data is managed separately. */
71
+ forget: (account: AccountRef) => Effect.Effect<void, BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, never>;
72
+ connections: Effect.Effect<AccountSummary[], BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, never>;
73
+ };
74
+ export type AuthenticationClient = ReturnType<typeof makeAuthenticationClient>;
75
+ //#endregion
76
+ //# sourceMappingURL=authentication.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authentication.d.ts","names":["_$__types_js0.Connection"],"sources":["../src/authentication.ts"],"mappings":";;;;;YAOY;WACC;WACA;;iBAGI,uBAAuB;WAC3B;WACA;WACA;;;;;wBAcG,yBAAyB;WAC5B,SAAS;WACT,wBAAwB;;EAWX,QAAA;aAAW;aAAgC;;;IAIpC,SAAA,QAAA,YAAU;;;wBAfNA;;OAe2B,sBAAG,OAAA;;;;;;;;;;;;MAGQ;;IAC3C,WAAA,gBAAM,OAAA;;;;;;;;;;;;MAG+C;;;EAGlC,wBAAA,2BAAM,sBAAmB,OAAA;IAGlD;;;EAIiB,gBAAA,2BAAM,mBAAgB,OAAA;IAEjB;;;EAErB,UAAA,SAAA,eAAU,OAAA,aAAA;;EAUX,SAAA,SAAA,eAAU,OAAA,aAAA;;;YAkDxB,uBAAuB,kBAAkB"}
@@ -0,0 +1,95 @@
1
+ import { makeOAuthAuthorizationClient } from "./authorization.js";
2
+ import { BackendError } from "@party-stack/ontology-backend";
3
+ import { Effect, Schema } from "effect";
4
+ import * as q from "@party-stack/ontology-spec/query";
5
+ //#region src/authentication.ts
6
+ const invalid = () => new BackendError({
7
+ operation: "connect.client",
8
+ kind: "InvalidResponse",
9
+ retryable: false,
10
+ message: "Connect returned an invalid response."
11
+ });
12
+ const ConnectionResult = Schema.Struct({ connectionId: Schema.NonEmptyString });
13
+ /** Effect-native commands and inventory queries over an ordinary Connect backend.
14
+ * Authentication actions execute directly; callers own the backend's Scope.
15
+ */
16
+ function makeAuthenticationClient(options) {
17
+ const apply = (name, parameters) => options.backend.applyAction({
18
+ id: crypto.randomUUID(),
19
+ name,
20
+ parameters
21
+ });
22
+ const create = (name, parameters) => apply(name, parameters).pipe(Effect.flatMap((receipt) => Schema.decodeUnknownEffect(ConnectionResult)(receipt.result).pipe(Effect.mapError(invalid))));
23
+ return {
24
+ oauth: (settings) => {
25
+ const oauth = makeOAuthAuthorizationClient({
26
+ ...options,
27
+ ...settings
28
+ });
29
+ return {
30
+ ...oauth,
31
+ signIn: (input) => oauth.signIn(input).pipe(Effect.map((account) => ({
32
+ ...account,
33
+ kind: "oauth"
34
+ }))),
35
+ complete: (url) => oauth.complete(url).pipe(Effect.map((account) => account && {
36
+ ...account,
37
+ kind: "oauth"
38
+ }))
39
+ };
40
+ },
41
+ attachExternalSession: (serviceInstanceId, sessionId) => create("attachExternalSession", {
42
+ serviceInstanceId,
43
+ sessionId
44
+ }).pipe(Effect.map((result) => ({
45
+ kind: "external-session",
46
+ id: result.connectionId
47
+ }))),
48
+ connectApiKey: (serviceInstanceId, apiKey) => create("connectApiKey", {
49
+ serviceInstanceId,
50
+ apiKey
51
+ }).pipe(Effect.map((result) => ({
52
+ kind: "api-key",
53
+ id: result.connectionId
54
+ }))),
55
+ signOut: (account) => apply(account.kind === "oauth" ? "disconnectConnection" : account.kind === "api-key" ? "disconnectApiKey" : "disconnectExternalSession", { connectionId: account.id }).pipe(Effect.asVoid),
56
+ /** Remove a saved account. Downloaded application data is managed separately. */
57
+ forget: (account) => apply(account.kind === "oauth" ? "forgetConnection" : account.kind === "api-key" ? "forgetApiKey" : "forgetExternalSession", { connectionId: account.id }).pipe(Effect.asVoid),
58
+ connections: Effect.gen(function* () {
59
+ const types = [
60
+ "OAuthConnection",
61
+ "ApiKeyConnection",
62
+ "ExternalSessionConnection"
63
+ ];
64
+ const result = yield* options.backend.query({ select: types.map((objectType) => q.sub(objectType, {
65
+ from: {
66
+ source: { objectType },
67
+ binding: "c"
68
+ },
69
+ select: [
70
+ "id",
71
+ "title",
72
+ "userId",
73
+ "status"
74
+ ].map((name) => q.selectField(name, q.field("c", name)))
75
+ })) });
76
+ return (yield* Effect.forEach(types, (objectType) => Schema.decodeUnknownEffect(Schema.Array(Schema.Struct({
77
+ id: Schema.String,
78
+ title: Schema.String,
79
+ userId: Schema.optional(Schema.String),
80
+ status: Schema.Literals([
81
+ "active",
82
+ "needs-auth",
83
+ "inactive"
84
+ ])
85
+ })))(result[objectType]).pipe(Effect.mapError(invalid), Effect.map((rows) => rows.map((row) => ({
86
+ ...row,
87
+ kind: objectType === "OAuthConnection" ? "oauth" : objectType === "ApiKeyConnection" ? "api-key" : "external-session"
88
+ })))))).flat();
89
+ })
90
+ };
91
+ }
92
+ //#endregion
93
+ export { makeAuthenticationClient };
94
+
95
+ //# sourceMappingURL=authentication.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authentication.js","names":[],"sources":["../src/authentication.ts"],"sourcesContent":["import { BackendError } from \"@party-stack/ontology-backend\";\nimport * as q from \"@party-stack/ontology-spec/query\";\nimport { Effect, Schema } from \"effect\";\nimport { makeOAuthAuthorizationClient } from \"./authorization.js\";\nimport type { OntologyBackendService } from \"@party-stack/ontology-backend\";\nimport type { BrowserAuthentication } from \"@party-stack/runtime\";\n\nexport type AccountRef = {\n readonly kind: \"oauth\" | \"api-key\" | \"external-session\";\n readonly id: string;\n};\n\nexport interface AccountSummary extends AccountRef {\n readonly userId?: string;\n readonly title: string;\n readonly status: \"active\" | \"needs-auth\" | \"inactive\";\n}\nconst invalid = () =>\n new BackendError({\n operation: \"connect.client\",\n kind: \"InvalidResponse\",\n retryable: false,\n message: \"Connect returned an invalid response.\",\n });\nconst ConnectionResult = Schema.Struct({ connectionId: Schema.NonEmptyString });\n\n/** Effect-native commands and inventory queries over an ordinary Connect backend.\n * Authentication actions execute directly; callers own the backend's Scope.\n */\nexport function makeAuthenticationClient(options: {\n readonly backend: OntologyBackendService;\n readonly browserAuthentication?: BrowserAuthentication;\n}) {\n const apply = (name: string, parameters: Record<string, unknown>) =>\n options.backend.applyAction({ id: crypto.randomUUID(), name, parameters });\n const create = (name: string, parameters: Record<string, unknown>) =>\n apply(name, parameters).pipe(\n Effect.flatMap((receipt) =>\n Schema.decodeUnknownEffect(ConnectionResult)(receipt.result).pipe(Effect.mapError(invalid))\n )\n );\n return {\n oauth: (settings: { readonly applicationId: string; readonly redirectUrl: string }) => {\n const oauth = makeOAuthAuthorizationClient({ ...options, ...settings });\n return {\n ...oauth,\n signIn: (input?: Parameters<typeof oauth.signIn>[0]) =>\n oauth\n .signIn(input)\n .pipe(Effect.map((account) => ({ ...account, kind: \"oauth\" as const }))),\n complete: (url: string) =>\n oauth\n .complete(url)\n .pipe(Effect.map((account) => account && { ...account, kind: \"oauth\" as const })),\n };\n },\n attachExternalSession: (serviceInstanceId: string, sessionId: string) =>\n create(\"attachExternalSession\", { serviceInstanceId, sessionId }).pipe(\n Effect.map((result) => ({\n kind: \"external-session\" as const,\n id: result.connectionId,\n }))\n ),\n connectApiKey: (serviceInstanceId: string, apiKey: string) =>\n create(\"connectApiKey\", { serviceInstanceId, apiKey }).pipe(\n Effect.map((result) => ({ kind: \"api-key\" as const, id: result.connectionId }))\n ),\n signOut: (account: AccountRef) =>\n apply(\n account.kind === \"oauth\"\n ? \"disconnectConnection\"\n : account.kind === \"api-key\"\n ? \"disconnectApiKey\"\n : \"disconnectExternalSession\",\n { connectionId: account.id }\n ).pipe(Effect.asVoid),\n /** Remove a saved account. Downloaded application data is managed separately. */\n forget: (account: AccountRef) =>\n apply(\n account.kind === \"oauth\"\n ? \"forgetConnection\"\n : account.kind === \"api-key\"\n ? \"forgetApiKey\"\n : \"forgetExternalSession\",\n { connectionId: account.id }\n ).pipe(Effect.asVoid),\n connections: Effect.gen(function* () {\n const types = [\"OAuthConnection\", \"ApiKeyConnection\", \"ExternalSessionConnection\"] as const;\n const result = yield* options.backend.query({\n select: types.map((objectType) =>\n q.sub(objectType, {\n from: { source: { objectType }, binding: \"c\" },\n select: [\"id\", \"title\", \"userId\", \"status\"].map((name) =>\n q.selectField(name, q.field(\"c\", name))\n ),\n })\n ),\n });\n const groups = yield* Effect.forEach(types, (objectType) =>\n Schema.decodeUnknownEffect(\n Schema.Array(\n Schema.Struct({\n id: Schema.String,\n title: Schema.String,\n userId: Schema.optional(Schema.String),\n status: Schema.Literals([\"active\", \"needs-auth\", \"inactive\"]),\n })\n )\n )(result[objectType]).pipe(\n Effect.mapError(invalid),\n Effect.map((rows) =>\n rows.map((row): AccountSummary => ({\n ...row,\n kind:\n objectType === \"OAuthConnection\"\n ? \"oauth\"\n : objectType === \"ApiKeyConnection\"\n ? \"api-key\"\n : \"external-session\",\n }))\n )\n )\n );\n return groups.flat();\n }),\n };\n}\nexport type AuthenticationClient = ReturnType<typeof makeAuthenticationClient>;\n"],"mappings":";;;;;AAiBA,MAAM,gBACF,IAAI,aAAa;CACb,WAAW;CACX,MAAM;CACN,WAAW;CACX,SAAS;AACb,CAAC;AACL,MAAM,mBAAmB,OAAO,OAAO,EAAE,cAAc,OAAO,eAAe,CAAC;;;;AAK9E,SAAgB,yBAAyB,SAGtC;CACC,MAAM,SAAS,MAAc,eACzB,QAAQ,QAAQ,YAAY;EAAE,IAAI,OAAO,WAAW;EAAG;EAAM;CAAW,CAAC;CAC7E,MAAM,UAAU,MAAc,eAC1B,MAAM,MAAM,UAAU,CAAC,CAAC,KACpB,OAAO,SAAS,YACZ,OAAO,oBAAoB,gBAAgB,CAAC,CAAC,QAAQ,MAAM,CAAC,CAAC,KAAK,OAAO,SAAS,OAAO,CAAC,CAC9F,CACJ;CACJ,OAAO;EACH,QAAQ,aAA+E;GACnF,MAAM,QAAQ,6BAA6B;IAAE,GAAG;IAAS,GAAG;GAAS,CAAC;GACtE,OAAO;IACH,GAAG;IACH,SAAS,UACL,MACK,OAAO,KAAK,CAAC,CACb,KAAK,OAAO,KAAK,aAAa;KAAE,GAAG;KAAS,MAAM;IAAiB,EAAE,CAAC;IAC/E,WAAW,QACP,MACK,SAAS,GAAG,CAAC,CACb,KAAK,OAAO,KAAK,YAAY,WAAW;KAAE,GAAG;KAAS,MAAM;IAAiB,CAAC,CAAC;GAC5F;EACJ;EACA,wBAAwB,mBAA2B,cAC/C,OAAO,yBAAyB;GAAE;GAAmB;EAAU,CAAC,CAAC,CAAC,KAC9D,OAAO,KAAK,YAAY;GACpB,MAAM;GACN,IAAI,OAAO;EACf,EAAE,CACN;EACJ,gBAAgB,mBAA2B,WACvC,OAAO,iBAAiB;GAAE;GAAmB;EAAO,CAAC,CAAC,CAAC,KACnD,OAAO,KAAK,YAAY;GAAE,MAAM;GAAoB,IAAI,OAAO;EAAa,EAAE,CAClF;EACJ,UAAU,YACN,MACI,QAAQ,SAAS,UACX,yBACA,QAAQ,SAAS,YACf,qBACA,6BACR,EAAE,cAAc,QAAQ,GAAG,CAC/B,CAAC,CAAC,KAAK,OAAO,MAAM;;EAExB,SAAS,YACL,MACI,QAAQ,SAAS,UACX,qBACA,QAAQ,SAAS,YACf,iBACA,yBACR,EAAE,cAAc,QAAQ,GAAG,CAC/B,CAAC,CAAC,KAAK,OAAO,MAAM;EACxB,aAAa,OAAO,IAAI,aAAa;GACjC,MAAM,QAAQ;IAAC;IAAmB;IAAoB;GAA2B;GACjF,MAAM,SAAS,OAAO,QAAQ,QAAQ,MAAM,EACxC,QAAQ,MAAM,KAAK,eACf,EAAE,IAAI,YAAY;IACd,MAAM;KAAE,QAAQ,EAAE,WAAW;KAAG,SAAS;IAAI;IAC7C,QAAQ;KAAC;KAAM;KAAS;KAAU;IAAQ,CAAC,CAAC,KAAK,SAC7C,EAAE,YAAY,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC,CAC1C;GACJ,CAAC,CACL,EACJ,CAAC;GA0BD,QAAO,OAzBe,OAAO,QAAQ,QAAQ,eACzC,OAAO,oBACH,OAAO,MACH,OAAO,OAAO;IACV,IAAI,OAAO;IACX,OAAO,OAAO;IACd,QAAQ,OAAO,SAAS,OAAO,MAAM;IACrC,QAAQ,OAAO,SAAS;KAAC;KAAU;KAAc;IAAU,CAAC;GAChE,CAAC,CACL,CACJ,CAAC,CAAC,OAAO,WAAW,CAAC,CAAC,KAClB,OAAO,SAAS,OAAO,GACvB,OAAO,KAAK,SACR,KAAK,KAAK,SAAyB;IAC/B,GAAG;IACH,MACI,eAAe,oBACT,UACA,eAAe,qBACb,YACA;GAChB,EAAE,CACN,CACJ,CACJ,EAAA,CACc,KAAK;EACvB,CAAC;CACL;AACJ"}
@@ -0,0 +1,43 @@
1
+ import { Connection } from "./types.js";
2
+ import { BackendError, OntologyBackendService } from "@party-stack/ontology-backend";
3
+ import { Effect } from "effect";
4
+ import { OntologyIR } from "@party-stack/ontology-spec";
5
+ import { BrowserAuthentication, BrowserAuthenticationPresentation } from "@party-stack/runtime";
6
+ //#region src/authorization.d.ts
7
+ /** A credential owner's native backend plus its fixed authorization binding.
8
+ * Transports project this policy before exposing the backend to a caller.
9
+ */
10
+ export interface OAuthAuthorizationSource {
11
+ readonly backend: OntologyBackendService;
12
+ readonly ir: OntologyIR;
13
+ readonly context: {
14
+ readonly applicationId: string;
15
+ readonly principalId: string;
16
+ readonly redirectUrl: string;
17
+ };
18
+ }
19
+ export interface OAuthAuthorizationClient {
20
+ readonly redirectUrl: string;
21
+ readonly signIn: (options?: {
22
+ browserPresentation?: BrowserAuthenticationPresentation;
23
+ connectionId?: string;
24
+ }) => Effect.Effect<Connection<"active"> & {
25
+ readonly id: string;
26
+ }, BackendError>;
27
+ readonly complete: (callbackUrl: string) => Effect.Effect<(Connection<"active"> & {
28
+ readonly id: string;
29
+ }) | undefined, BackendError>;
30
+ }
31
+ /** Only connection identity/status is readable. Credentials and PKCE attempts stay private. */
32
+ export declare const oauthAuthorizationOntology: OntologyIR;
33
+ /** Trusted in-process counterpart of the server's IR policy binding. */
34
+ export declare function bindOAuthAuthorizationBackend(source: OAuthAuthorizationSource): OntologyBackendService;
35
+ /** Browser orchestration over ordinary Connect actions; no dedicated OAuth RPCs. */
36
+ export declare function makeOAuthAuthorizationClient(options: {
37
+ backend: OntologyBackendService;
38
+ applicationId?: string;
39
+ redirectUrl: string;
40
+ browserAuthentication?: BrowserAuthentication;
41
+ }): OAuthAuthorizationClient;
42
+ //#endregion
43
+ //# sourceMappingURL=authorization.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authorization.d.ts","names":[],"sources":["../src/authorization.ts"],"mappings":";;;;;;;;;iBAYiB;WACJ,SAAS;WACT,IAAI;WACJ;aACI;aACA;aACA;;;iBAIA;WACJ;WACA,SAAS;IACd,sBAAsB;IACtB;QACE,OAAO,OAAO;aAAkC;KAAc;WAC3D,WACL,wBACC,OAAO,QAAQ;aAAkC;kBAA2B;;;qBAIxE,4BAA4B;;wBAiDzB,8BAA8B,QAAQ,2BAA2B;;wBAoCjE,6BAA6B;EACzC,SAAS;EACT;EACA;EACA,wBAAwB;IACxB"}