@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.
- package/LICENSE +21 -0
- package/README.md +189 -2
- package/lib/ServiceConnector.d.ts +68 -0
- package/lib/ServiceConnector.d.ts.map +1 -0
- package/lib/ServiceConnector.js +1 -0
- package/lib/acquireConfiguredConnection.d.ts +32 -0
- package/lib/acquireConfiguredConnection.d.ts.map +1 -0
- package/lib/acquireConfiguredConnection.js +54 -0
- package/lib/acquireConfiguredConnection.js.map +1 -0
- package/lib/authentication.d.ts +76 -0
- package/lib/authentication.d.ts.map +1 -0
- package/lib/authentication.js +95 -0
- package/lib/authentication.js.map +1 -0
- package/lib/authorization.d.ts +43 -0
- package/lib/authorization.d.ts.map +1 -0
- package/lib/authorization.js +175 -0
- package/lib/authorization.js.map +1 -0
- package/lib/core/accessToken.d.ts +10 -0
- package/lib/core/accessToken.d.ts.map +1 -0
- package/lib/core/accessToken.js +87 -0
- package/lib/core/accessToken.js.map +1 -0
- package/lib/core/backend.d.ts +33 -0
- package/lib/core/backend.d.ts.map +1 -0
- package/lib/core/backend.js +249 -0
- package/lib/core/backend.js.map +1 -0
- package/lib/core/errors.d.ts +13 -0
- package/lib/core/errors.d.ts.map +1 -0
- package/lib/core/errors.js +26 -0
- package/lib/core/errors.js.map +1 -0
- package/lib/core/maintenance.d.ts +11 -0
- package/lib/core/maintenance.d.ts.map +1 -0
- package/lib/core/maintenance.js +21 -0
- package/lib/core/maintenance.js.map +1 -0
- package/lib/core/migrate.d.ts +18 -0
- package/lib/core/migrate.d.ts.map +1 -0
- package/lib/core/migrate.js +71 -0
- package/lib/core/migrate.js.map +1 -0
- package/lib/core/oauth.d.ts +27 -0
- package/lib/core/oauth.d.ts.map +1 -0
- package/lib/core/oauth.js +82 -0
- package/lib/core/oauth.js.map +1 -0
- package/lib/core/oauthAuthority.d.ts +90 -0
- package/lib/core/oauthAuthority.d.ts.map +1 -0
- package/lib/core/oauthAuthority.js +382 -0
- package/lib/core/oauthAuthority.js.map +1 -0
- package/lib/core/store.d.ts +48 -0
- package/lib/core/store.d.ts.map +1 -0
- package/lib/core/store.js +92 -0
- package/lib/core/store.js.map +1 -0
- package/lib/createDefaultConnectionEgressHandlers.d.ts +5 -0
- package/lib/createDefaultConnectionEgressHandlers.d.ts.map +1 -0
- package/lib/createDefaultConnectionEgressHandlers.js +20 -0
- package/lib/createDefaultConnectionEgressHandlers.js.map +1 -0
- package/lib/index.d.ts +20 -0
- package/lib/index.js +17 -0
- package/lib/makeConnectManager.d.ts +90 -0
- package/lib/makeConnectManager.d.ts.map +1 -0
- package/lib/makeConnectManager.js +91 -0
- package/lib/makeConnectManager.js.map +1 -0
- package/lib/oauth/storage.d.ts +9 -0
- package/lib/oauth/storage.d.ts.map +1 -0
- package/lib/oauth/storage.js +16 -0
- package/lib/oauth/storage.js.map +1 -0
- package/lib/publicOntology.d.ts +17 -0
- package/lib/publicOntology.d.ts.map +1 -0
- package/lib/publicOntology.js +86 -0
- package/lib/publicOntology.js.map +1 -0
- package/lib/server/index.d.ts +33 -0
- package/lib/server/index.d.ts.map +1 -0
- package/lib/server/index.js +119 -0
- package/lib/server/index.js.map +1 -0
- package/lib/serverClient.d.ts +28 -0
- package/lib/serverClient.d.ts.map +1 -0
- package/lib/serverClient.js +67 -0
- package/lib/serverClient.js.map +1 -0
- package/lib/serviceConnections.d.ts +39 -0
- package/lib/serviceConnections.d.ts.map +1 -0
- package/lib/serviceConnections.js +277 -0
- package/lib/serviceConnections.js.map +1 -0
- package/lib/spec/index.d.ts +958 -0
- package/lib/spec/index.d.ts.map +1 -0
- package/lib/spec/index.js +565 -0
- package/lib/spec/index.js.map +1 -0
- package/lib/toWebEgress.d.ts +12 -0
- package/lib/toWebEgress.d.ts.map +1 -0
- package/lib/toWebEgress.js +28 -0
- package/lib/toWebEgress.js.map +1 -0
- package/lib/types.d.ts +44 -0
- package/lib/types.d.ts.map +1 -0
- package/lib/types.js +25 -0
- package/lib/types.js.map +1 -0
- package/lib/withHttpAuthenticationErrors.d.ts +5 -0
- package/lib/withHttpAuthenticationErrors.d.ts.map +1 -0
- package/lib/withHttpAuthenticationErrors.js +20 -0
- package/lib/withHttpAuthenticationErrors.js.map +1 -0
- package/package.json +34 -3
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { connectOntology } from "./spec/index.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
|
+
import { o } from "@party-stack/ontology-spec";
|
|
6
|
+
//#region src/authorization.ts
|
|
7
|
+
/** Only connection identity/status is readable. Credentials and PKCE attempts stay private. */
|
|
8
|
+
const oauthAuthorizationOntology = {
|
|
9
|
+
...connectOntology,
|
|
10
|
+
context: { type: o.struct({ fields: [
|
|
11
|
+
{
|
|
12
|
+
name: "applicationId",
|
|
13
|
+
displayName: "Connector",
|
|
14
|
+
type: o.string({})
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
name: "principalId",
|
|
18
|
+
displayName: "Principal",
|
|
19
|
+
type: o.string({})
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
name: "redirectUrl",
|
|
23
|
+
displayName: "Redirect URL",
|
|
24
|
+
type: o.string({})
|
|
25
|
+
}
|
|
26
|
+
] }) },
|
|
27
|
+
policy: {
|
|
28
|
+
objects: { select: [q.sub("connections", {
|
|
29
|
+
from: {
|
|
30
|
+
source: { objectType: "OAuthConnection" },
|
|
31
|
+
binding: "c"
|
|
32
|
+
},
|
|
33
|
+
where: q.eq(q.field("c", "application"), q.context("applicationId")),
|
|
34
|
+
select: [
|
|
35
|
+
"id",
|
|
36
|
+
"userId",
|
|
37
|
+
"status"
|
|
38
|
+
].map((name) => q.selectField(name, q.field("c", name)))
|
|
39
|
+
})] },
|
|
40
|
+
actions: [{
|
|
41
|
+
actionType: "beginAuthorization",
|
|
42
|
+
check: q.literal(true),
|
|
43
|
+
bind: [
|
|
44
|
+
"applicationId",
|
|
45
|
+
"principalId",
|
|
46
|
+
"redirectUrl"
|
|
47
|
+
].map((parameter) => ({
|
|
48
|
+
parameter,
|
|
49
|
+
expression: q.context(parameter)
|
|
50
|
+
})),
|
|
51
|
+
additionalObjects: { select: [q.sub("application", {
|
|
52
|
+
from: {
|
|
53
|
+
source: { objectType: "OAuthApplication" },
|
|
54
|
+
binding: "application"
|
|
55
|
+
},
|
|
56
|
+
where: q.eq(q.field("application", "id"), q.context("applicationId")),
|
|
57
|
+
select: [q.selectField("id", q.field("application", "id"))]
|
|
58
|
+
})] }
|
|
59
|
+
}, {
|
|
60
|
+
actionType: "completeAuthorization",
|
|
61
|
+
check: q.literal(true),
|
|
62
|
+
bind: [{
|
|
63
|
+
parameter: "principalId",
|
|
64
|
+
expression: q.context("principalId")
|
|
65
|
+
}]
|
|
66
|
+
}]
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
/** Trusted in-process counterpart of the server's IR policy binding. */
|
|
70
|
+
function bindOAuthAuthorizationBackend(source) {
|
|
71
|
+
return {
|
|
72
|
+
...source.backend,
|
|
73
|
+
applyAction: (request) => {
|
|
74
|
+
const parameters = request.name === "beginAuthorization" ? {
|
|
75
|
+
...request.parameters,
|
|
76
|
+
...source.context
|
|
77
|
+
} : request.name === "completeAuthorization" ? {
|
|
78
|
+
...request.parameters,
|
|
79
|
+
principalId: source.context.principalId
|
|
80
|
+
} : void 0;
|
|
81
|
+
return parameters ? source.backend.applyAction({
|
|
82
|
+
...request,
|
|
83
|
+
parameters
|
|
84
|
+
}) : Effect.fail(new BackendError({
|
|
85
|
+
operation: "authorization",
|
|
86
|
+
kind: "NotImplemented",
|
|
87
|
+
retryable: false,
|
|
88
|
+
message: "Unknown authorization action."
|
|
89
|
+
}));
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
const Started = Schema.Struct({
|
|
94
|
+
id: Schema.String,
|
|
95
|
+
authorizationUrl: Schema.String
|
|
96
|
+
});
|
|
97
|
+
const Completed = Schema.Struct({ connectionId: Schema.String });
|
|
98
|
+
const Account = Schema.Struct({
|
|
99
|
+
userId: Schema.String,
|
|
100
|
+
status: Schema.Literal("active")
|
|
101
|
+
});
|
|
102
|
+
const invalid = () => new BackendError({
|
|
103
|
+
operation: "authorization",
|
|
104
|
+
kind: "InvalidResponse",
|
|
105
|
+
retryable: false,
|
|
106
|
+
message: "Authorization returned an invalid response."
|
|
107
|
+
});
|
|
108
|
+
/** Browser orchestration over ordinary Connect actions; no dedicated OAuth RPCs. */
|
|
109
|
+
function makeOAuthAuthorizationClient(options) {
|
|
110
|
+
const apply = (name, parameters) => options.backend.applyAction({
|
|
111
|
+
id: crypto.randomUUID(),
|
|
112
|
+
name,
|
|
113
|
+
parameters
|
|
114
|
+
});
|
|
115
|
+
const complete = Effect.fn("Connect.authorization.complete")(function* (callbackUrl) {
|
|
116
|
+
if (!(yield* Effect.try({
|
|
117
|
+
try: () => new URL(callbackUrl),
|
|
118
|
+
catch: invalid
|
|
119
|
+
})).searchParams.has("state")) return;
|
|
120
|
+
const receipt = yield* apply("completeAuthorization", { callbackUrl });
|
|
121
|
+
const { connectionId } = yield* Schema.decodeUnknownEffect(Completed)(receipt.result).pipe(Effect.mapError(invalid));
|
|
122
|
+
const rows = yield* options.backend.query({ select: [q.sub("connection", {
|
|
123
|
+
from: {
|
|
124
|
+
source: { objectType: "OAuthConnection" },
|
|
125
|
+
binding: "c"
|
|
126
|
+
},
|
|
127
|
+
where: q.eq(q.field("c", "id"), q.literal(connectionId)),
|
|
128
|
+
page: { limit: 1 },
|
|
129
|
+
select: [q.selectField("userId", q.field("c", "userId")), q.selectField("status", q.field("c", "status"))]
|
|
130
|
+
})] });
|
|
131
|
+
const [account] = yield* Schema.decodeUnknownEffect(Schema.Array(Account))(rows.connection).pipe(Effect.mapError(invalid));
|
|
132
|
+
if (!account) return yield* invalid();
|
|
133
|
+
return {
|
|
134
|
+
id: connectionId,
|
|
135
|
+
userId: account.userId,
|
|
136
|
+
state: { status: "active" }
|
|
137
|
+
};
|
|
138
|
+
});
|
|
139
|
+
return {
|
|
140
|
+
redirectUrl: options.redirectUrl,
|
|
141
|
+
complete,
|
|
142
|
+
signIn: Effect.fn("Connect.authorization.signIn")(function* (settings) {
|
|
143
|
+
const browser = options.browserAuthentication;
|
|
144
|
+
if (!browser) return yield* new BackendError({
|
|
145
|
+
operation: "authorization",
|
|
146
|
+
kind: "InvalidConfiguration",
|
|
147
|
+
retryable: false,
|
|
148
|
+
message: "Interactive authorization requires a browser authentication capability."
|
|
149
|
+
});
|
|
150
|
+
const presentation = yield* browser.start({
|
|
151
|
+
redirectUrl: options.redirectUrl,
|
|
152
|
+
presentation: settings?.browserPresentation
|
|
153
|
+
});
|
|
154
|
+
const receipt = yield* apply("beginAuthorization", {
|
|
155
|
+
applicationId: options.applicationId,
|
|
156
|
+
redirectUrl: options.redirectUrl,
|
|
157
|
+
connectionId: settings?.connectionId
|
|
158
|
+
});
|
|
159
|
+
const started = yield* Schema.decodeUnknownEffect(Started)(receipt.result).pipe(Effect.mapError(invalid));
|
|
160
|
+
const { callbackUrl } = yield* presentation.open(started.authorizationUrl);
|
|
161
|
+
const connection = yield* complete(callbackUrl);
|
|
162
|
+
if (!connection) return yield* invalid();
|
|
163
|
+
return connection;
|
|
164
|
+
}, Effect.scoped, Effect.mapError((cause) => cause instanceof BackendError ? cause : new BackendError({
|
|
165
|
+
operation: "authorization.presentation",
|
|
166
|
+
kind: "Unavailable",
|
|
167
|
+
retryable: false,
|
|
168
|
+
message: cause.message
|
|
169
|
+
})))
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
//#endregion
|
|
173
|
+
export { bindOAuthAuthorizationBackend, makeOAuthAuthorizationClient, oauthAuthorizationOntology };
|
|
174
|
+
|
|
175
|
+
//# sourceMappingURL=authorization.js.map
|
|
@@ -0,0 +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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ACA,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"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { BackendError, OntologyBackendService } from "@party-stack/ontology-backend";
|
|
2
|
+
import { Effect } from "effect";
|
|
3
|
+
//#region src/core/accessToken.d.ts
|
|
4
|
+
/** Egress convenience over ordinary reads, refresh action and property decryption.
|
|
5
|
+
* The supplied backend may be local or remote and must authorize token-property
|
|
6
|
+
* access. This adds no alternate permission path or credential-returning RPC.
|
|
7
|
+
*/
|
|
8
|
+
export declare const connectionAccessToken: (backend: OntologyBackendService, connectionId: string) => Effect.Effect<string, BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, never>;
|
|
9
|
+
//#endregion
|
|
10
|
+
//# sourceMappingURL=accessToken.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"accessToken.d.ts","names":[],"sources":["../../src/core/accessToken.ts"],"mappings":";;;;;;;qBAgBa,wBAAqB,SAAA,wBAAA,yBAAA,OAAA,eAAA"}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { BackendError, EncryptedValueSchema } from "@party-stack/ontology-backend";
|
|
2
|
+
import { Clock, Effect, Schema } from "effect";
|
|
3
|
+
import * as q from "@party-stack/ontology-spec/query";
|
|
4
|
+
import { TemporalTimestamp } from "@party-stack/ontology-spec/effect";
|
|
5
|
+
//#region src/core/accessToken.ts
|
|
6
|
+
const State = Schema.Struct({
|
|
7
|
+
status: Schema.Literals([
|
|
8
|
+
"active",
|
|
9
|
+
"needs-auth",
|
|
10
|
+
"inactive"
|
|
11
|
+
]),
|
|
12
|
+
accessToken: Schema.optional(EncryptedValueSchema),
|
|
13
|
+
accessTokenExpiresAt: Schema.optional(TemporalTimestamp)
|
|
14
|
+
});
|
|
15
|
+
/** Egress convenience over ordinary reads, refresh action and property decryption.
|
|
16
|
+
* The supplied backend may be local or remote and must authorize token-property
|
|
17
|
+
* access. This adds no alternate permission path or credential-returning RPC.
|
|
18
|
+
*/
|
|
19
|
+
const connectionAccessToken = Effect.fn("Connect.accessToken")(function* (backend, connectionId) {
|
|
20
|
+
if (!backend.encrypted) return yield* new BackendError({
|
|
21
|
+
operation: "decrypt",
|
|
22
|
+
kind: "NotImplemented",
|
|
23
|
+
retryable: false,
|
|
24
|
+
message: "Connection property decryption is unavailable."
|
|
25
|
+
});
|
|
26
|
+
const read = Effect.fnUntraced(function* () {
|
|
27
|
+
const result = yield* backend.query({ select: [q.sub("connections", {
|
|
28
|
+
from: {
|
|
29
|
+
source: { objectType: "OAuthConnection" },
|
|
30
|
+
binding: "connection"
|
|
31
|
+
},
|
|
32
|
+
where: q.eq(q.field("connection", "id"), q.literal(connectionId)),
|
|
33
|
+
select: [
|
|
34
|
+
"status",
|
|
35
|
+
"accessToken",
|
|
36
|
+
"accessTokenExpiresAt"
|
|
37
|
+
].map((name) => q.selectField(name, q.field("connection", name)))
|
|
38
|
+
})] });
|
|
39
|
+
const row = (yield* Schema.decodeUnknownEffect(Schema.Array(State))(result.connections).pipe(Effect.mapError(() => new BackendError({
|
|
40
|
+
operation: "connect.read",
|
|
41
|
+
kind: "InvalidResponse",
|
|
42
|
+
retryable: false,
|
|
43
|
+
message: "Connection state is invalid."
|
|
44
|
+
}))))[0];
|
|
45
|
+
if (!row) return yield* new BackendError({
|
|
46
|
+
operation: "connect.read",
|
|
47
|
+
kind: "NotFound",
|
|
48
|
+
retryable: false,
|
|
49
|
+
message: "Connection is unavailable."
|
|
50
|
+
});
|
|
51
|
+
return row;
|
|
52
|
+
});
|
|
53
|
+
let current = yield* read();
|
|
54
|
+
const now = yield* Clock.currentTimeMillis;
|
|
55
|
+
if (!current.accessToken || current.status === "inactive" || current.accessTokenExpiresAt && current.accessTokenExpiresAt.epochMilliseconds <= now + 5e3) {
|
|
56
|
+
yield* backend.applyAction({
|
|
57
|
+
id: crypto.randomUUID(),
|
|
58
|
+
name: "refreshConnection",
|
|
59
|
+
parameters: { connectionId }
|
|
60
|
+
});
|
|
61
|
+
current = yield* read();
|
|
62
|
+
}
|
|
63
|
+
if (!current.accessToken) return yield* new BackendError({
|
|
64
|
+
operation: "connect.read",
|
|
65
|
+
kind: "Unauthenticated",
|
|
66
|
+
retryable: false,
|
|
67
|
+
message: "Access credentials are unavailable."
|
|
68
|
+
});
|
|
69
|
+
const result = yield* backend.encrypted.decrypt({
|
|
70
|
+
...current.accessToken,
|
|
71
|
+
source: {
|
|
72
|
+
objectType: "OAuthConnection",
|
|
73
|
+
primaryKey: connectionId,
|
|
74
|
+
property: "accessToken"
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
return yield* Schema.decodeUnknownEffect(Schema.String)(result.value).pipe(Effect.mapError(() => new BackendError({
|
|
78
|
+
operation: "decrypt",
|
|
79
|
+
kind: "InvalidResponse",
|
|
80
|
+
retryable: false,
|
|
81
|
+
message: "Connection returned an invalid access token."
|
|
82
|
+
})));
|
|
83
|
+
});
|
|
84
|
+
//#endregion
|
|
85
|
+
export { connectionAccessToken };
|
|
86
|
+
|
|
87
|
+
//# sourceMappingURL=accessToken.js.map
|
|
@@ -0,0 +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"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { ConnectError } from "./errors.js";
|
|
2
|
+
import { ConnectStore } from "./store.js";
|
|
3
|
+
import { OAuthAuthorityOptions, OAuthAuthorityService } from "./oauthAuthority.js";
|
|
4
|
+
import { ServiceConnector } from "../ServiceConnector.js";
|
|
5
|
+
import { ActionRequest, BackendError, OntologyBackendService } from "@party-stack/ontology-backend";
|
|
6
|
+
import { Effect, Scope } from "effect";
|
|
7
|
+
//#region src/core/backend.d.ts
|
|
8
|
+
export type ConnectActionHandler = (request: ActionRequest) => Effect.Effect<unknown, BackendError | ConnectError, Scope.Scope>;
|
|
9
|
+
export declare const connectBackendError: (error: ConnectError) => BackendError<"Conflict" | "Forbidden" | "InvalidConfiguration" | "InvalidRequest" | "NotFound" | "Unauthenticated" | "Unavailable">;
|
|
10
|
+
/** Private credential authority exposed through ordinary ontology reads/actions.
|
|
11
|
+
* Apply a server policy before serving untrusted callers: connection/token records,
|
|
12
|
+
* principal binding, callback URLs and application access belong to that policy.
|
|
13
|
+
* Call these actions directly through the backend/protocol, not a durable UI outbox.
|
|
14
|
+
*/
|
|
15
|
+
export declare const makeConnectBackend: (options: Omit<OAuthAuthorityOptions, "oauth" | "store"> & {
|
|
16
|
+
tables: import("@party-stack/ontology-storage/tables").TablesService;
|
|
17
|
+
namespace: string;
|
|
18
|
+
ir?: import("@party-stack/ontology-spec").OntologyIR;
|
|
19
|
+
maintenance?: false | {
|
|
20
|
+
readonly intervalMs?: number;
|
|
21
|
+
};
|
|
22
|
+
} & {
|
|
23
|
+
readonly oauth?: OAuthAuthorityOptions["oauth"];
|
|
24
|
+
readonly services?: readonly ServiceConnector[];
|
|
25
|
+
/** Declared application workflow actions; parameters and results use the supplied IR. */
|
|
26
|
+
readonly actionHandlers?: Readonly<Record<string, ConnectActionHandler>>;
|
|
27
|
+
}) => Effect.Effect<{
|
|
28
|
+
backend: OntologyBackendService;
|
|
29
|
+
connect: OAuthAuthorityService;
|
|
30
|
+
store: ConnectStore;
|
|
31
|
+
}, BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, Scope.Scope>;
|
|
32
|
+
//#endregion
|
|
33
|
+
//# sourceMappingURL=backend.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"backend.d.ts","names":["_$__oauthAuthority_js0.OAuthAuthorityService","_$__store_js0.ConnectStore"],"sources":["../../src/core/backend.ts"],"mappings":";;;;;;;YAeY,wBACR,SAAS,kBACR,OAAO,gBAAgB,eAAe,cAAc,MAAM;qBAElD,sBAAmB,OAAW,iBAAY;;;;;;qBA6B1C,qBAAkB,SAAA,KAAA;;;;;;;;WAIE,QAAA;WACG,oBAAS;;WAEH,iBAAA,SAAS,eAAe;;;;;GAuVjE,iWAAA,MAAA"}
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import { connectOntology } from "../spec/index.js";
|
|
2
|
+
import { connectError } from "./errors.js";
|
|
3
|
+
import { maintainConnect } from "./maintenance.js";
|
|
4
|
+
import { makeOAuthAuthority } from "./oauthAuthority.js";
|
|
5
|
+
import { makeConnectPersistence } from "./store.js";
|
|
6
|
+
import { BackendError, makePropertyDecryption, schemaValidationIssues } from "@party-stack/ontology-backend";
|
|
7
|
+
import { and, eq, field } from "@party-stack/ontology-storage";
|
|
8
|
+
import { Clock, Effect, Redacted, Schema } from "effect";
|
|
9
|
+
import { compileEffectSchemas } from "@party-stack/ontology-spec/effect";
|
|
10
|
+
//#region src/core/backend.ts
|
|
11
|
+
const connectBackendError = (error) => new BackendError({
|
|
12
|
+
operation: "connect",
|
|
13
|
+
retryable: error.retryable,
|
|
14
|
+
kind: error.kind === "Configuration" ? "InvalidConfiguration" : error.kind === "NeedsAuthentication" ? "Unauthenticated" : error.kind === "InvalidAttempt" ? "InvalidRequest" : error.kind === "Busy" ? "Conflict" : error.kind === "Provider" || error.kind === "Storage" ? "Unavailable" : error.kind,
|
|
15
|
+
message: error.message,
|
|
16
|
+
actionOutcome: error.kind === "Provider" || error.kind === "Storage" || error.kind === "NeedsAuthentication" ? "unknown" : "not-committed"
|
|
17
|
+
});
|
|
18
|
+
/** Private credential authority exposed through ordinary ontology reads/actions.
|
|
19
|
+
* Apply a server policy before serving untrusted callers: connection/token records,
|
|
20
|
+
* principal binding, callback URLs and application access belong to that policy.
|
|
21
|
+
* Call these actions directly through the backend/protocol, not a durable UI outbox.
|
|
22
|
+
*/
|
|
23
|
+
const makeConnectBackend = Effect.fn("Connect.backend")(function* (options) {
|
|
24
|
+
for (const name of Object.keys(options.actionHandlers ?? {})) if (connectOntology.actionTypes.some((action) => action.name === name) || !(options.ir ?? connectOntology).actionTypes.some((action) => action.name === name)) return yield* new BackendError({
|
|
25
|
+
operation: "connect.configure",
|
|
26
|
+
kind: "InvalidConfiguration",
|
|
27
|
+
retryable: false,
|
|
28
|
+
message: "Application handlers must declare a new action in the Connect ontology."
|
|
29
|
+
});
|
|
30
|
+
const { store, backend: persistence } = yield* makeConnectPersistence({
|
|
31
|
+
...options,
|
|
32
|
+
maintenance: false
|
|
33
|
+
});
|
|
34
|
+
const services = new Map(options.services?.map((service) => [service.service, service]));
|
|
35
|
+
if (services.size !== (options.services?.length ?? 0)) return yield* connectBackendError(connectError("Configuration", "Service connector names must be unique."));
|
|
36
|
+
const connect = yield* makeOAuthAuthority({
|
|
37
|
+
...options,
|
|
38
|
+
store,
|
|
39
|
+
oauth: options.oauth ?? ((input) => {
|
|
40
|
+
const service = services.get(input.serviceInstance.service);
|
|
41
|
+
return service?.oauth ? service.oauth({
|
|
42
|
+
...input,
|
|
43
|
+
values: options.values
|
|
44
|
+
}) : Effect.fail(connectError("Configuration", "This service does not support OAuth."));
|
|
45
|
+
})
|
|
46
|
+
});
|
|
47
|
+
const instance = Effect.fnUntraced(function* (id) {
|
|
48
|
+
const value = yield* store.get("ServiceInstance", id);
|
|
49
|
+
if (!value) return yield* connectError("NotFound", "Service instance is unavailable.");
|
|
50
|
+
const service = services.get(value.service);
|
|
51
|
+
if (!service) return yield* connectError("Configuration", "Service connector is unavailable.");
|
|
52
|
+
return {
|
|
53
|
+
value,
|
|
54
|
+
service
|
|
55
|
+
};
|
|
56
|
+
});
|
|
57
|
+
const schemas = compileEffectSchemas(options.ir ?? connectOntology);
|
|
58
|
+
const { storage: _storage, ...reads } = persistence;
|
|
59
|
+
const backend = {
|
|
60
|
+
...reads,
|
|
61
|
+
name: "connect",
|
|
62
|
+
maintenance: Effect.gen(function* () {
|
|
63
|
+
yield* persistence.maintenance ?? Effect.void;
|
|
64
|
+
yield* connect.collectExpired().pipe(Effect.mapError(connectBackendError));
|
|
65
|
+
}),
|
|
66
|
+
encrypted: makePropertyDecryption({
|
|
67
|
+
ir: options.ir ?? connectOntology,
|
|
68
|
+
get: (type, key) => persistence.storage.read((tx) => tx.get(type, key)),
|
|
69
|
+
decrypt: (handle) => options.values.decrypt(Schema.Unknown, handle).pipe(Effect.mapError(() => new BackendError({
|
|
70
|
+
operation: "decrypt",
|
|
71
|
+
kind: "Unavailable",
|
|
72
|
+
retryable: false,
|
|
73
|
+
message: "Encrypted value is unavailable."
|
|
74
|
+
})))
|
|
75
|
+
}),
|
|
76
|
+
supportsIdempotency: false,
|
|
77
|
+
applyAction: Effect.fn("Connect.applyAction")(function* (request) {
|
|
78
|
+
const definition = (options.ir ?? connectOntology).actionTypes.find((action) => action.name === request.name);
|
|
79
|
+
if (!definition) return yield* new BackendError({
|
|
80
|
+
operation: "applyAction",
|
|
81
|
+
kind: "NotImplemented",
|
|
82
|
+
retryable: false,
|
|
83
|
+
actionOutcome: "not-committed",
|
|
84
|
+
message: "Unknown Connect action."
|
|
85
|
+
});
|
|
86
|
+
if (request.attachmentUploads?.length) return yield* new BackendError({
|
|
87
|
+
operation: "applyAction",
|
|
88
|
+
kind: "InvalidRequest",
|
|
89
|
+
retryable: false,
|
|
90
|
+
actionOutcome: "not-committed",
|
|
91
|
+
message: "Connect actions do not accept attachments."
|
|
92
|
+
});
|
|
93
|
+
const args = yield* Schema.decodeUnknownEffect(Schema.toEncoded(schemas.actionParameterSchemas[request.name]))(request.parameters).pipe(Effect.mapError((error) => new BackendError({
|
|
94
|
+
operation: "applyAction",
|
|
95
|
+
kind: "ValidationFailed",
|
|
96
|
+
retryable: false,
|
|
97
|
+
actionOutcome: "not-committed",
|
|
98
|
+
message: "Action parameters do not match their definition.",
|
|
99
|
+
issues: schemaValidationIssues(error)
|
|
100
|
+
})));
|
|
101
|
+
const text = (name) => args[name];
|
|
102
|
+
const optionalText = (name) => typeof args[name] === "string" ? args[name] : void 0;
|
|
103
|
+
const result = yield* Effect.gen(function* () {
|
|
104
|
+
const handlers = options.actionHandlers;
|
|
105
|
+
const handler = handlers && Object.hasOwn(handlers, definition.name) ? handlers[definition.name] : void 0;
|
|
106
|
+
if (handler && !connectOntology.actionTypes.some((action) => action.name === definition.name)) return yield* Effect.scoped(handler({
|
|
107
|
+
...request,
|
|
108
|
+
parameters: args
|
|
109
|
+
}));
|
|
110
|
+
switch (definition.name) {
|
|
111
|
+
case "beginAuthorization": return yield* connect.begin({
|
|
112
|
+
applicationId: text("applicationId"),
|
|
113
|
+
principalId: optionalText("principalId"),
|
|
114
|
+
redirectUrl: text("redirectUrl"),
|
|
115
|
+
returnUrl: optionalText("returnUrl"),
|
|
116
|
+
connectionId: optionalText("connectionId")
|
|
117
|
+
});
|
|
118
|
+
case "completeAuthorization": return { connectionId: (yield* connect.complete({
|
|
119
|
+
callbackUrl: text("callbackUrl"),
|
|
120
|
+
principalId: optionalText("principalId")
|
|
121
|
+
})).id };
|
|
122
|
+
case "connectClientCredentials": return { connectionId: (yield* connect.clientCredentials({
|
|
123
|
+
applicationId: text("applicationId"),
|
|
124
|
+
connectionId: optionalText("connectionId")
|
|
125
|
+
})).id };
|
|
126
|
+
case "refreshConnection": return { connectionId: (yield* connect.refresh(text("connectionId"))).id };
|
|
127
|
+
case "disconnectConnection": return yield* connect.disconnect(text("connectionId"));
|
|
128
|
+
case "forgetConnection": return yield* connect.forget(text("connectionId"));
|
|
129
|
+
case "connectApiKey": {
|
|
130
|
+
const { value, service } = yield* instance(text("serviceInstanceId"));
|
|
131
|
+
if (!service.apiKey) return yield* connectError("Configuration", "This service does not accept API keys.");
|
|
132
|
+
const identity = yield* service.apiKey({
|
|
133
|
+
serviceInstance: value,
|
|
134
|
+
apiKey: text("apiKey")
|
|
135
|
+
});
|
|
136
|
+
if (identity.expiresAt && identity.expiresAt.epochMilliseconds <= (yield* Clock.currentTimeMillis)) return yield* connectError("NeedsAuthentication", "The API key has expired.");
|
|
137
|
+
const id = JSON.stringify([value.id, identity.userId]);
|
|
138
|
+
const apiKey = yield* options.values.encrypt(Schema.String, text("apiKey")).pipe(Effect.mapError(() => connectError("Storage", "Could not encrypt the API key.")));
|
|
139
|
+
yield* store.put("ApiKeyConnection", {
|
|
140
|
+
id,
|
|
141
|
+
serviceInstance: value.id,
|
|
142
|
+
userId: identity.userId,
|
|
143
|
+
title: identity.title ?? identity.userId,
|
|
144
|
+
status: "active",
|
|
145
|
+
apiKey,
|
|
146
|
+
expiresAt: identity.expiresAt
|
|
147
|
+
});
|
|
148
|
+
return { connectionId: id };
|
|
149
|
+
}
|
|
150
|
+
case "attachExternalSession": {
|
|
151
|
+
const { value, service } = yield* instance(text("serviceInstanceId"));
|
|
152
|
+
if (!service.externalSession) return yield* connectError("Configuration", "This service does not accept external sessions.");
|
|
153
|
+
const sessionId = text("sessionId");
|
|
154
|
+
const identity = yield* service.externalSession({
|
|
155
|
+
serviceInstance: value,
|
|
156
|
+
sessionId
|
|
157
|
+
});
|
|
158
|
+
if (identity.expiresAt && identity.expiresAt.epochMilliseconds <= (yield* Clock.currentTimeMillis)) return yield* connectError("NeedsAuthentication", "The external session has expired.");
|
|
159
|
+
return { connectionId: yield* store.transaction(Effect.gen(function* () {
|
|
160
|
+
const sameSession = (yield* store.load("ExternalSessionConnection", {
|
|
161
|
+
where: and(eq(field("serviceInstance"), value.id), eq(field("sessionId"), sessionId)),
|
|
162
|
+
limit: 1
|
|
163
|
+
}))[0];
|
|
164
|
+
if (sameSession && sameSession.userId !== identity.userId) return yield* connectError("Forbidden", "The external session identity changed.");
|
|
165
|
+
const id = (yield* store.load("ExternalSessionConnection", {
|
|
166
|
+
where: and(eq(field("serviceInstance"), value.id), eq(field("userId"), identity.userId)),
|
|
167
|
+
limit: 1
|
|
168
|
+
}))[0]?.id ?? JSON.stringify([value.id, identity.userId]);
|
|
169
|
+
yield* store.put("ExternalSessionConnection", {
|
|
170
|
+
id,
|
|
171
|
+
serviceInstance: value.id,
|
|
172
|
+
userId: identity.userId,
|
|
173
|
+
title: identity.title ?? identity.userId,
|
|
174
|
+
status: "active",
|
|
175
|
+
sessionId,
|
|
176
|
+
expiresAt: identity.expiresAt
|
|
177
|
+
});
|
|
178
|
+
return id;
|
|
179
|
+
})) };
|
|
180
|
+
}
|
|
181
|
+
case "disconnectApiKey":
|
|
182
|
+
case "forgetApiKey": return yield* store.transaction(Effect.gen(function* () {
|
|
183
|
+
const current = yield* store.get("ApiKeyConnection", text("connectionId"));
|
|
184
|
+
if (!current && definition.name === "forgetApiKey") return;
|
|
185
|
+
if (!current) return yield* connectError("NotFound", "Connection is unavailable.");
|
|
186
|
+
if (current.apiKey) yield* options.values.evict(current.apiKey).pipe(Effect.mapError(() => connectError("Storage", "Credential deletion failed.", true)));
|
|
187
|
+
if (definition.name === "forgetApiKey") return yield* store.delete("ApiKeyConnection", current.id);
|
|
188
|
+
yield* store.put("ApiKeyConnection", {
|
|
189
|
+
...current,
|
|
190
|
+
apiKey: void 0,
|
|
191
|
+
status: "inactive"
|
|
192
|
+
});
|
|
193
|
+
}));
|
|
194
|
+
case "disconnectExternalSession":
|
|
195
|
+
case "forgetExternalSession": {
|
|
196
|
+
const current = yield* store.transaction(Effect.gen(function* () {
|
|
197
|
+
const current = yield* store.get("ExternalSessionConnection", text("connectionId"));
|
|
198
|
+
if (!current && definition.name === "forgetExternalSession") return;
|
|
199
|
+
if (!current) return yield* connectError("NotFound", "Connection is unavailable.");
|
|
200
|
+
if (definition.name === "forgetExternalSession") yield* store.delete("ExternalSessionConnection", current.id);
|
|
201
|
+
else yield* store.put("ExternalSessionConnection", {
|
|
202
|
+
...current,
|
|
203
|
+
status: "inactive"
|
|
204
|
+
});
|
|
205
|
+
return current;
|
|
206
|
+
}));
|
|
207
|
+
if (!current) return;
|
|
208
|
+
const { value, service } = yield* instance(current.serviceInstance);
|
|
209
|
+
yield* service.disconnectExternalSession?.({
|
|
210
|
+
serviceInstance: value,
|
|
211
|
+
sessionId: current.sessionId
|
|
212
|
+
}) ?? Effect.void;
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
default: return yield* new BackendError({
|
|
216
|
+
operation: "applyAction",
|
|
217
|
+
kind: "NotImplemented",
|
|
218
|
+
retryable: false,
|
|
219
|
+
actionOutcome: "not-committed",
|
|
220
|
+
message: "Connect action has no implementation."
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
}).pipe(Effect.mapError((error) => error instanceof BackendError ? error : connectBackendError(error)));
|
|
224
|
+
const codec = schemas.actionReturnSchemas[request.name];
|
|
225
|
+
const encoded = codec ? yield* Schema.encodeEffect(Schema.toCodecJson(codec))(result).pipe(Effect.mapError((cause) => new BackendError({
|
|
226
|
+
operation: "applyAction.result",
|
|
227
|
+
kind: "InvalidResponse",
|
|
228
|
+
retryable: false,
|
|
229
|
+
message: "Connect returned an invalid action result.",
|
|
230
|
+
cause: Redacted.make(cause)
|
|
231
|
+
}))) : void 0;
|
|
232
|
+
return {
|
|
233
|
+
operationId: request.id,
|
|
234
|
+
outcome: "committed",
|
|
235
|
+
result: encoded
|
|
236
|
+
};
|
|
237
|
+
})
|
|
238
|
+
};
|
|
239
|
+
yield* maintainConnect(backend.maintenance, options.maintenance);
|
|
240
|
+
return {
|
|
241
|
+
backend,
|
|
242
|
+
connect,
|
|
243
|
+
store
|
|
244
|
+
};
|
|
245
|
+
}, Effect.mapError((error) => error instanceof BackendError ? error : connectBackendError(error)));
|
|
246
|
+
//#endregion
|
|
247
|
+
export { connectBackendError, makeConnectBackend };
|
|
248
|
+
|
|
249
|
+
//# sourceMappingURL=backend.js.map
|