@party-stack/connect 0.0.0-stage → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +189 -2
- package/lib/ServiceConnector.d.ts +68 -0
- package/lib/ServiceConnector.d.ts.map +1 -0
- package/lib/ServiceConnector.js +1 -0
- package/lib/acquireConfiguredConnection.d.ts +32 -0
- package/lib/acquireConfiguredConnection.d.ts.map +1 -0
- package/lib/acquireConfiguredConnection.js +54 -0
- package/lib/acquireConfiguredConnection.js.map +1 -0
- package/lib/authentication.d.ts +76 -0
- package/lib/authentication.d.ts.map +1 -0
- package/lib/authentication.js +95 -0
- package/lib/authentication.js.map +1 -0
- package/lib/authorization.d.ts +43 -0
- package/lib/authorization.d.ts.map +1 -0
- package/lib/authorization.js +175 -0
- package/lib/authorization.js.map +1 -0
- package/lib/core/accessToken.d.ts +10 -0
- package/lib/core/accessToken.d.ts.map +1 -0
- package/lib/core/accessToken.js +87 -0
- package/lib/core/accessToken.js.map +1 -0
- package/lib/core/backend.d.ts +33 -0
- package/lib/core/backend.d.ts.map +1 -0
- package/lib/core/backend.js +249 -0
- package/lib/core/backend.js.map +1 -0
- package/lib/core/errors.d.ts +13 -0
- package/lib/core/errors.d.ts.map +1 -0
- package/lib/core/errors.js +26 -0
- package/lib/core/errors.js.map +1 -0
- package/lib/core/maintenance.d.ts +11 -0
- package/lib/core/maintenance.d.ts.map +1 -0
- package/lib/core/maintenance.js +21 -0
- package/lib/core/maintenance.js.map +1 -0
- package/lib/core/migrate.d.ts +18 -0
- package/lib/core/migrate.d.ts.map +1 -0
- package/lib/core/migrate.js +71 -0
- package/lib/core/migrate.js.map +1 -0
- package/lib/core/oauth.d.ts +27 -0
- package/lib/core/oauth.d.ts.map +1 -0
- package/lib/core/oauth.js +82 -0
- package/lib/core/oauth.js.map +1 -0
- package/lib/core/oauthAuthority.d.ts +90 -0
- package/lib/core/oauthAuthority.d.ts.map +1 -0
- package/lib/core/oauthAuthority.js +382 -0
- package/lib/core/oauthAuthority.js.map +1 -0
- package/lib/core/store.d.ts +48 -0
- package/lib/core/store.d.ts.map +1 -0
- package/lib/core/store.js +92 -0
- package/lib/core/store.js.map +1 -0
- package/lib/createDefaultConnectionEgressHandlers.d.ts +5 -0
- package/lib/createDefaultConnectionEgressHandlers.d.ts.map +1 -0
- package/lib/createDefaultConnectionEgressHandlers.js +20 -0
- package/lib/createDefaultConnectionEgressHandlers.js.map +1 -0
- package/lib/index.d.ts +20 -0
- package/lib/index.js +17 -0
- package/lib/makeConnectManager.d.ts +90 -0
- package/lib/makeConnectManager.d.ts.map +1 -0
- package/lib/makeConnectManager.js +91 -0
- package/lib/makeConnectManager.js.map +1 -0
- package/lib/oauth/storage.d.ts +9 -0
- package/lib/oauth/storage.d.ts.map +1 -0
- package/lib/oauth/storage.js +16 -0
- package/lib/oauth/storage.js.map +1 -0
- package/lib/publicOntology.d.ts +17 -0
- package/lib/publicOntology.d.ts.map +1 -0
- package/lib/publicOntology.js +86 -0
- package/lib/publicOntology.js.map +1 -0
- package/lib/server/index.d.ts +33 -0
- package/lib/server/index.d.ts.map +1 -0
- package/lib/server/index.js +119 -0
- package/lib/server/index.js.map +1 -0
- package/lib/serverClient.d.ts +28 -0
- package/lib/serverClient.d.ts.map +1 -0
- package/lib/serverClient.js +67 -0
- package/lib/serverClient.js.map +1 -0
- package/lib/serviceConnections.d.ts +39 -0
- package/lib/serviceConnections.d.ts.map +1 -0
- package/lib/serviceConnections.js +277 -0
- package/lib/serviceConnections.js.map +1 -0
- package/lib/spec/index.d.ts +958 -0
- package/lib/spec/index.d.ts.map +1 -0
- package/lib/spec/index.js +565 -0
- package/lib/spec/index.js.map +1 -0
- package/lib/toWebEgress.d.ts +12 -0
- package/lib/toWebEgress.d.ts.map +1 -0
- package/lib/toWebEgress.js +28 -0
- package/lib/toWebEgress.js.map +1 -0
- package/lib/types.d.ts +44 -0
- package/lib/types.d.ts.map +1 -0
- package/lib/types.js +25 -0
- package/lib/types.js.map +1 -0
- package/lib/withHttpAuthenticationErrors.d.ts +5 -0
- package/lib/withHttpAuthenticationErrors.d.ts.map +1 -0
- package/lib/withHttpAuthenticationErrors.js +20 -0
- package/lib/withHttpAuthenticationErrors.js.map +1 -0
- package/package.json +34 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"backend.js","names":[],"sources":["../../src/core/backend.ts"],"sourcesContent":["import { BackendError, schemaValidationIssues, makePropertyDecryption } from \"@party-stack/ontology-backend\";\nimport { compileEffectSchemas } from \"@party-stack/ontology-spec/effect\";\nimport { and, eq, field } from \"@party-stack/ontology-storage\";\nimport { Clock, Effect, Redacted, Schema } from \"effect\";\nimport { connectOntology } from \"../spec/index.js\";\nimport { connectError } from \"./errors.js\";\nimport { maintainConnect } from \"./maintenance.js\";\nimport { makeOAuthAuthority } from \"./oauthAuthority.js\";\nimport { makeConnectPersistence } from \"./store.js\";\nimport type { ServiceConnector } from \"../ServiceConnector.js\";\nimport type { ConnectError } from \"./errors.js\";\nimport type { OAuthAuthorityOptions } from \"./oauthAuthority.js\";\nimport type { ActionRequest, OntologyBackendService } from \"@party-stack/ontology-backend\";\nimport type { Scope } from \"effect\";\n\nexport type ConnectActionHandler = (\n request: ActionRequest\n) => Effect.Effect<unknown, BackendError | ConnectError, Scope.Scope>;\n\nexport const connectBackendError = (error: ConnectError) =>\n new BackendError({\n operation: \"connect\",\n retryable: error.retryable,\n kind:\n error.kind === \"Configuration\"\n ? \"InvalidConfiguration\"\n : error.kind === \"NeedsAuthentication\"\n ? \"Unauthenticated\"\n : error.kind === \"InvalidAttempt\"\n ? \"InvalidRequest\"\n : error.kind === \"Busy\"\n ? \"Conflict\"\n : error.kind === \"Provider\" || error.kind === \"Storage\"\n ? \"Unavailable\"\n : error.kind,\n message: error.message,\n // An exchange can fail after the oauth has consumed a single-use credential.\n actionOutcome:\n error.kind === \"Provider\" || error.kind === \"Storage\" || error.kind === \"NeedsAuthentication\"\n ? \"unknown\"\n : \"not-committed\",\n });\n\n/** Private credential authority exposed through ordinary ontology reads/actions.\n * Apply a server policy before serving untrusted callers: connection/token records,\n * principal binding, callback URLs and application access belong to that policy.\n * Call these actions directly through the backend/protocol, not a durable UI outbox.\n */\nexport const makeConnectBackend = Effect.fn(\"Connect.backend\")(\n function* (\n options: Omit<OAuthAuthorityOptions, \"store\" | \"oauth\"> &\n Parameters<typeof makeConnectPersistence>[0] & {\n readonly oauth?: OAuthAuthorityOptions[\"oauth\"];\n readonly services?: readonly ServiceConnector[];\n /** Declared application workflow actions; parameters and results use the supplied IR. */\n readonly actionHandlers?: Readonly<Record<string, ConnectActionHandler>>;\n }\n ) {\n for (const name of Object.keys(options.actionHandlers ?? {})) {\n if (\n connectOntology.actionTypes.some((action) => action.name === name) ||\n !(options.ir ?? connectOntology).actionTypes.some((action) => action.name === name)\n )\n return yield* new BackendError({\n operation: \"connect.configure\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"Application handlers must declare a new action in the Connect ontology.\",\n });\n }\n const { store, backend: persistence } = yield* makeConnectPersistence({\n ...options,\n maintenance: false,\n });\n const services = new Map(options.services?.map((service) => [service.service, service]));\n if (services.size !== (options.services?.length ?? 0))\n return yield* connectBackendError(\n connectError(\"Configuration\", \"Service connector names must be unique.\")\n );\n const connect = yield* makeOAuthAuthority({\n ...options,\n store,\n oauth:\n options.oauth ??\n ((input) => {\n const service = services.get(input.serviceInstance.service);\n return service?.oauth\n ? service.oauth({ ...input, values: options.values })\n : Effect.fail(connectError(\"Configuration\", \"This service does not support OAuth.\"));\n }),\n });\n const instance = Effect.fnUntraced(function* (id: string) {\n const value = yield* store.get(\"ServiceInstance\", id);\n if (!value) return yield* connectError(\"NotFound\", \"Service instance is unavailable.\");\n const service = services.get(value.service);\n if (!service) return yield* connectError(\"Configuration\", \"Service connector is unavailable.\");\n return { value, service };\n });\n const schemas = compileEffectSchemas(options.ir ?? connectOntology);\n // This is an adapter over a multi-transaction workflow, not an owned mutator.\n // Do not expose `storage`: server projection must check/bind inputs before IO,\n // rather than relying on the owned backend's transaction authorization hook.\n const { storage: _storage, ...reads } = persistence;\n const backend: OntologyBackendService = {\n ...reads,\n name: \"connect\",\n maintenance: Effect.gen(function* () {\n yield* persistence.maintenance ?? Effect.void;\n yield* connect.collectExpired().pipe(Effect.mapError(connectBackendError));\n }),\n encrypted: makePropertyDecryption({\n ir: options.ir ?? connectOntology,\n get: (type, key) => persistence.storage.read((tx) => tx.get(type, key)),\n decrypt: (handle) =>\n options.values.decrypt(Schema.Unknown, handle).pipe(\n Effect.mapError(\n () =>\n new BackendError({\n operation: \"decrypt\",\n kind: \"Unavailable\",\n retryable: false,\n message: \"Encrypted value is unavailable.\",\n })\n )\n ),\n }),\n // Native claims prevent repeated code exchange; they do not make arbitrary\n // action IDs idempotent. A generic durable workflow/result hook is future work.\n supportsIdempotency: false,\n applyAction: Effect.fn(\"Connect.applyAction\")(function* (request) {\n const definition = (options.ir ?? connectOntology).actionTypes.find(\n (action) => action.name === request.name\n );\n if (!definition)\n return yield* new BackendError({\n operation: \"applyAction\",\n kind: \"NotImplemented\",\n retryable: false,\n actionOutcome: \"not-committed\",\n message: \"Unknown Connect action.\",\n });\n if (request.attachmentUploads?.length)\n return yield* new BackendError({\n operation: \"applyAction\",\n kind: \"InvalidRequest\",\n retryable: false,\n actionOutcome: \"not-committed\",\n message: \"Connect actions do not accept attachments.\",\n });\n const args = yield* Schema.decodeUnknownEffect(\n Schema.toEncoded(schemas.actionParameterSchemas[request.name]!)\n )(request.parameters).pipe(\n Effect.mapError(\n (error) =>\n new BackendError({\n operation: \"applyAction\",\n kind: \"ValidationFailed\",\n retryable: false,\n actionOutcome: \"not-committed\",\n message: \"Action parameters do not match their definition.\",\n issues: schemaValidationIssues(error),\n })\n )\n );\n const text = (name: string) => args[name] as string;\n const optionalText = (name: string) =>\n typeof args[name] === \"string\" ? (args[name] as string) : undefined;\n const result = yield* Effect.gen(function* () {\n const handlers = options.actionHandlers;\n const handler =\n handlers && Object.hasOwn(handlers, definition.name)\n ? handlers[definition.name]\n : undefined;\n if (\n handler &&\n !connectOntology.actionTypes.some((action) => action.name === definition.name)\n )\n return yield* Effect.scoped(handler({ ...request, parameters: args }));\n switch (definition.name) {\n case \"beginAuthorization\":\n return yield* connect.begin({\n applicationId: text(\"applicationId\"),\n principalId: optionalText(\"principalId\"),\n redirectUrl: text(\"redirectUrl\"),\n returnUrl: optionalText(\"returnUrl\"),\n connectionId: optionalText(\"connectionId\"),\n });\n case \"completeAuthorization\":\n return {\n connectionId: (yield* connect.complete({\n callbackUrl: text(\"callbackUrl\"),\n principalId: optionalText(\"principalId\"),\n })).id,\n };\n case \"connectClientCredentials\":\n return {\n connectionId: (yield* connect.clientCredentials({\n applicationId: text(\"applicationId\"),\n connectionId: optionalText(\"connectionId\"),\n })).id,\n };\n case \"refreshConnection\":\n return { connectionId: (yield* connect.refresh(text(\"connectionId\"))).id };\n case \"disconnectConnection\":\n return yield* connect.disconnect(text(\"connectionId\"));\n case \"forgetConnection\":\n return yield* connect.forget(text(\"connectionId\"));\n case \"connectApiKey\": {\n const { value, service } = yield* instance(text(\"serviceInstanceId\"));\n if (!service.apiKey)\n return yield* connectError(\n \"Configuration\",\n \"This service does not accept API keys.\"\n );\n const identity = yield* service.apiKey({\n serviceInstance: value,\n apiKey: text(\"apiKey\"),\n });\n if (\n identity.expiresAt &&\n identity.expiresAt.epochMilliseconds <= (yield* Clock.currentTimeMillis)\n )\n return yield* connectError(\"NeedsAuthentication\", \"The API key has expired.\");\n const id = JSON.stringify([value.id, identity.userId]);\n const apiKey = yield* options.values\n .encrypt(Schema.String, text(\"apiKey\"))\n .pipe(\n Effect.mapError(() =>\n connectError(\"Storage\", \"Could not encrypt the API key.\")\n )\n );\n yield* store.put(\"ApiKeyConnection\", {\n id,\n serviceInstance: value.id,\n userId: identity.userId,\n title: identity.title ?? identity.userId,\n status: \"active\",\n apiKey,\n expiresAt: identity.expiresAt,\n });\n return { connectionId: id };\n }\n case \"attachExternalSession\": {\n const { value, service } = yield* instance(text(\"serviceInstanceId\"));\n if (!service.externalSession)\n return yield* connectError(\n \"Configuration\",\n \"This service does not accept external sessions.\"\n );\n const sessionId = text(\"sessionId\");\n const identity = yield* service.externalSession({\n serviceInstance: value,\n sessionId,\n });\n if (\n identity.expiresAt &&\n identity.expiresAt.epochMilliseconds <= (yield* Clock.currentTimeMillis)\n )\n return yield* connectError(\n \"NeedsAuthentication\",\n \"The external session has expired.\"\n );\n const id = yield* store.transaction(\n Effect.gen(function* () {\n const sameSession = (yield* store.load(\"ExternalSessionConnection\", {\n where: and(\n eq(field(\"serviceInstance\"), value.id),\n eq(field(\"sessionId\"), sessionId)\n ),\n limit: 1,\n }))[0];\n if (sameSession && sameSession.userId !== identity.userId)\n return yield* connectError(\n \"Forbidden\",\n \"The external session identity changed.\"\n );\n const previous = (yield* store.load(\"ExternalSessionConnection\", {\n where: and(\n eq(field(\"serviceInstance\"), value.id),\n eq(field(\"userId\"), identity.userId)\n ),\n limit: 1,\n }))[0];\n const id = previous?.id ?? JSON.stringify([value.id, identity.userId]);\n yield* store.put(\"ExternalSessionConnection\", {\n id,\n serviceInstance: value.id,\n userId: identity.userId,\n title: identity.title ?? identity.userId,\n status: \"active\",\n sessionId,\n expiresAt: identity.expiresAt,\n });\n return id;\n })\n );\n return { connectionId: id };\n }\n case \"disconnectApiKey\":\n case \"forgetApiKey\":\n return yield* store.transaction(\n Effect.gen(function* () {\n const current = yield* store.get(\n \"ApiKeyConnection\",\n text(\"connectionId\")\n );\n if (!current && definition.name === \"forgetApiKey\") return;\n if (!current)\n return yield* connectError(\"NotFound\", \"Connection is unavailable.\");\n if (current.apiKey)\n yield* options.values\n .evict(current.apiKey)\n .pipe(\n Effect.mapError(() =>\n connectError(\n \"Storage\",\n \"Credential deletion failed.\",\n true\n )\n )\n );\n if (definition.name === \"forgetApiKey\")\n return yield* store.delete(\"ApiKeyConnection\", current.id);\n yield* store.put(\"ApiKeyConnection\", {\n ...current,\n apiKey: undefined,\n status: \"inactive\",\n });\n })\n );\n case \"disconnectExternalSession\":\n case \"forgetExternalSession\": {\n const current = yield* store.transaction(\n Effect.gen(function* () {\n const current = yield* store.get(\n \"ExternalSessionConnection\",\n text(\"connectionId\")\n );\n if (!current && definition.name === \"forgetExternalSession\") return;\n if (!current)\n return yield* connectError(\"NotFound\", \"Connection is unavailable.\");\n if (definition.name === \"forgetExternalSession\")\n yield* store.delete(\"ExternalSessionConnection\", current.id);\n else\n yield* store.put(\"ExternalSessionConnection\", {\n ...current,\n status: \"inactive\",\n });\n return current;\n })\n );\n if (!current) return;\n // Detach first. Failed remote revocation cannot restore local access.\n const { value, service } = yield* instance(current.serviceInstance);\n yield* (\n service.disconnectExternalSession?.({\n serviceInstance: value,\n sessionId: current.sessionId,\n }) ?? Effect.void\n );\n return;\n }\n default:\n return yield* new BackendError({\n operation: \"applyAction\",\n kind: \"NotImplemented\",\n retryable: false,\n actionOutcome: \"not-committed\",\n message: \"Connect action has no implementation.\",\n });\n }\n }).pipe(\n Effect.mapError((error) =>\n error instanceof BackendError ? error : connectBackendError(error)\n )\n );\n const codec = schemas.actionReturnSchemas[request.name];\n const encoded = codec\n ? yield* Schema.encodeEffect(Schema.toCodecJson(codec))(result).pipe(\n Effect.mapError(\n (cause) =>\n new BackendError({\n operation: \"applyAction.result\",\n kind: \"InvalidResponse\",\n retryable: false,\n message: \"Connect returned an invalid action result.\",\n cause: Redacted.make(cause),\n })\n )\n )\n : undefined;\n return { operationId: request.id, outcome: \"committed\" as const, result: encoded };\n }),\n };\n yield* maintainConnect(backend.maintenance!, options.maintenance);\n return { backend, connect, store };\n },\n Effect.mapError((error) => (error instanceof BackendError ? error : connectBackendError(error)))\n);\n"],"mappings":";;;;;;;;;;AAmBA,MAAa,uBAAuB,UAChC,IAAI,aAAa;CACb,WAAW;CACX,WAAW,MAAM;CACjB,MACI,MAAM,SAAS,kBACT,yBACA,MAAM,SAAS,wBACb,oBACA,MAAM,SA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13 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
//#region src/core/errors.d.ts
|
|
3
|
+
declare const ConnectError_base: Schema.Class<ConnectError, Schema.TaggedStruct<"ConnectError", {
|
|
4
|
+
readonly kind: Schema.Literals<readonly ["Configuration", "NotFound", "Forbidden", "NeedsAuthentication", "Busy", "InvalidAttempt", "Provider", "Storage"]>;
|
|
5
|
+
readonly message: Schema.String;
|
|
6
|
+
readonly retryable: Schema.Boolean;
|
|
7
|
+
}>, import("effect/Cause").YieldableError>;
|
|
8
|
+
/** Provider bodies, codes, tokens and authorization URLs must never enter errors. */
|
|
9
|
+
export declare class ConnectError extends ConnectError_base {}
|
|
10
|
+
export declare const connectError: (kind: ConnectError["kind"], message: string, retryable?: boolean) => ConnectError;
|
|
11
|
+
//#endregion
|
|
12
|
+
export {};
|
|
13
|
+
//# sourceMappingURL=errors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.d.ts","names":[],"sources":["../../src/core/errors.ts"],"mappings":";;;;;;;;qBAGa,qBAAqB;qBAcrB,eAAY,MAAU,sBAAoB,iBAAiB,wBAAA"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
//#region src/core/errors.ts
|
|
3
|
+
/** Provider bodies, codes, tokens and authorization URLs must never enter errors. */
|
|
4
|
+
var ConnectError = class extends Schema.TaggedError()("ConnectError", {
|
|
5
|
+
kind: Schema.Literals([
|
|
6
|
+
"Configuration",
|
|
7
|
+
"NotFound",
|
|
8
|
+
"Forbidden",
|
|
9
|
+
"NeedsAuthentication",
|
|
10
|
+
"Busy",
|
|
11
|
+
"InvalidAttempt",
|
|
12
|
+
"Provider",
|
|
13
|
+
"Storage"
|
|
14
|
+
]),
|
|
15
|
+
message: Schema.String,
|
|
16
|
+
retryable: Schema.Boolean
|
|
17
|
+
}) {};
|
|
18
|
+
const connectError = (kind, message, retryable = false) => new ConnectError({
|
|
19
|
+
kind,
|
|
20
|
+
message,
|
|
21
|
+
retryable
|
|
22
|
+
});
|
|
23
|
+
//#endregion
|
|
24
|
+
export { ConnectError, connectError };
|
|
25
|
+
|
|
26
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","names":[],"sources":["../../src/core/errors.ts"],"sourcesContent":["import { Schema } from \"effect\";\n\n/** Provider bodies, codes, tokens and authorization URLs must never enter errors. */\nexport class ConnectError extends Schema.TaggedError<ConnectError>()(\"ConnectError\", {\n kind: Schema.Literals([\n \"Configuration\",\n \"NotFound\",\n \"Forbidden\",\n \"NeedsAuthentication\",\n \"Busy\",\n \"InvalidAttempt\",\n \"Provider\",\n \"Storage\",\n ]),\n message: Schema.String,\n retryable: Schema.Boolean,\n}) {}\nexport const connectError = (kind: ConnectError[\"kind\"], message: string, retryable = false) =>\n new ConnectError({ kind, message, retryable });\n"],"mappings":";;;AAGA,IAAa,eAAb,cAAkC,OAAO,YAA0B,CAAC,CAAC,gBAAgB;CACjF,MAAM,OAAO,SAAS;EAClB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACJ,CAAC;CACD,SAAS,OAAO;CAChB,WAAW,OAAO;AACtB,CAAC,CAAC,CAAC,CAAC;AACJ,MAAa,gBAAgB,MAA4B,SAAiB,YAAY,UAClF,IAAI,aAAa;CAAE;CAAM;CAAS;AAAU,CAAC"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { BackendError } from "@party-stack/ontology-backend";
|
|
2
|
+
import { Effect } from "effect";
|
|
3
|
+
//#region src/core/maintenance.d.ts
|
|
4
|
+
/** The credential backend owns one scoped sweep. Serverless hosts opt out and
|
|
5
|
+
* invoke backend.maintenance from their alarm/job instead.
|
|
6
|
+
*/
|
|
7
|
+
export declare const maintainConnect: (work: Effect.Effect<void, BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, never>, options: false | {
|
|
8
|
+
readonly intervalMs?: number;
|
|
9
|
+
} | undefined) => Effect.Effect<import("effect/Fiber").Fiber<never, never> | undefined, BackendError<"InvalidConfiguration">, import("effect/Scope").Scope>;
|
|
10
|
+
//#endregion
|
|
11
|
+
//# sourceMappingURL=maintenance.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"maintenance.d.ts","names":[],"sources":["../../src/core/maintenance.ts"],"mappings":";;;;;;qBAMa,kBAAe,MAAA,OAAA,aAAA,yWAAA;WAEiB;kBAmB3C,OAAA,8BAAA,iCAAA,6DAAA"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { BackendError } from "@party-stack/ontology-backend";
|
|
2
|
+
import { Effect } from "effect";
|
|
3
|
+
//#region src/core/maintenance.ts
|
|
4
|
+
/** The credential backend owns one scoped sweep. Serverless hosts opt out and
|
|
5
|
+
* invoke backend.maintenance from their alarm/job instead.
|
|
6
|
+
*/
|
|
7
|
+
const maintainConnect = Effect.fnUntraced(function* (work, options) {
|
|
8
|
+
const intervalMs = options && options.intervalMs !== void 0 ? options.intervalMs : 6e4;
|
|
9
|
+
if (!Number.isFinite(intervalMs) || intervalMs <= 0) return yield* new BackendError({
|
|
10
|
+
operation: "connect.maintenance",
|
|
11
|
+
kind: "InvalidConfiguration",
|
|
12
|
+
retryable: false,
|
|
13
|
+
message: "Connect maintenance interval must be positive and finite."
|
|
14
|
+
});
|
|
15
|
+
if (options === false) return;
|
|
16
|
+
return yield* Effect.forkScoped(Effect.forever(Effect.sleep(intervalMs).pipe(Effect.andThen(work), Effect.catch((error) => Effect.logWarning("Connect maintenance failed", { kind: error.kind })))));
|
|
17
|
+
});
|
|
18
|
+
//#endregion
|
|
19
|
+
export { maintainConnect };
|
|
20
|
+
|
|
21
|
+
//# sourceMappingURL=maintenance.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"maintenance.js","names":[],"sources":["../../src/core/maintenance.ts"],"sourcesContent":["import { BackendError } from \"@party-stack/ontology-backend\";\nimport { Effect } from \"effect\";\n\n/** The credential backend owns one scoped sweep. Serverless hosts opt out and\n * invoke backend.maintenance from their alarm/job instead.\n */\nexport const maintainConnect = Effect.fnUntraced(function* (\n work: Effect.Effect<void, BackendError>,\n options: false | { readonly intervalMs?: number } | undefined\n) {\n const intervalMs = options && options.intervalMs !== undefined ? options.intervalMs : 60_000;\n if (!Number.isFinite(intervalMs) || intervalMs <= 0)\n return yield* new BackendError({\n operation: \"connect.maintenance\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"Connect maintenance interval must be positive and finite.\",\n });\n if (options === false) return;\n return yield* Effect.forkScoped(\n Effect.forever(\n Effect.sleep(intervalMs).pipe(\n Effect.andThen(work),\n Effect.catch((error) => Effect.logWarning(\"Connect maintenance failed\", { kind: error.kind }))\n )\n )\n );\n});\n"],"mappings":";;;;;;AAMA,MAAa,kBAAkB,OAAO,WAAW,WAC7C,MACA,SACF;CACE,MAAM,aAAa,WAAW,QAAQ,eAAe,KAAA,IAAY,QAAQ,aAAa;CACtF,IAAI,CAAC,OAAO,SAAS,UAAU,KAAK,cAAc,GAC9C,OAAO,OAAO,IAAI,aAAa;EAC3B,WAAW;EACX,MAAM;EACN,WAAW;EACX,SAAS;CACb,CAAC;CACL,IAAI,YAAY,OAAO;CACvB,OAAO,OAAO,OAAO,WACjB,OAAO,QACH,OAAO,MAAM,UAAU,CAAC,CAAC,KACrB,OAAO,QAAQ,IAAI,GACnB,OAAO,OAAO,UAAU,OAAO,WAAW,8BAA8B,EAAE,MAAM,MAAM,KAAK,CAAC,CAAC,CACjG,CACJ,CACJ;AACJ,CAAC"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { ConnectError } from "./errors.js";
|
|
2
|
+
import { ConnectStore } from "./store.js";
|
|
3
|
+
import { Effect, Schema } from "effect";
|
|
4
|
+
import { OntologyIR } from "@party-stack/ontology-spec";
|
|
5
|
+
import { TablesService } from "@party-stack/ontology-storage/tables";
|
|
6
|
+
//#region src/core/migrate.d.ts
|
|
7
|
+
/** Import earlier Connect schemas without changing credential encryption AAD.
|
|
8
|
+
* New commits precede old-row deletion. A crash can repeat a batch but cannot replace
|
|
9
|
+
* an already imported/refreshed credential. Old journal cursors stay in the old namespace.
|
|
10
|
+
*/
|
|
11
|
+
export declare const migrateConnectCredentials: (options: {
|
|
12
|
+
tables: TablesService;
|
|
13
|
+
namespace: string;
|
|
14
|
+
ir: OntologyIR;
|
|
15
|
+
store: ConnectStore;
|
|
16
|
+
}) => Effect.Effect<void, ConnectError | import("@party-stack/ontology-storage/tables").OntologyStorageError | Schema.SchemaError, never>;
|
|
17
|
+
//#endregion
|
|
18
|
+
//# sourceMappingURL=migrate.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migrate.d.ts","names":["_$__errors_js0.ConnectError"],"sources":["../../src/core/migrate.ts"],"mappings":";;;;;;;;;;qBAWa,4BAAyB;EAC1B,QAAA;EACG;EACP,IAAA;EACG,OAAA;MAoET,OAAA,aApESA,8DAoET,uBAAA,OAAA"}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { Effect, Schema } from "effect";
|
|
2
|
+
import { compileEffectSchemas } from "@party-stack/ontology-spec/effect";
|
|
3
|
+
import { Table } from "@party-stack/ontology-storage/tables";
|
|
4
|
+
//#region src/core/migrate.ts
|
|
5
|
+
/** Import earlier Connect schemas without changing credential encryption AAD.
|
|
6
|
+
* New commits precede old-row deletion. A crash can repeat a batch but cannot replace
|
|
7
|
+
* an already imported/refreshed credential. Old journal cursors stay in the old namespace.
|
|
8
|
+
*/
|
|
9
|
+
const migrateConnectCredentials = Effect.fn("Connect.migrate")(function* (options) {
|
|
10
|
+
const schemas = compileEffectSchemas(options.ir).objectSchemas;
|
|
11
|
+
for (const source of [{
|
|
12
|
+
namespace: JSON.stringify([
|
|
13
|
+
options.namespace,
|
|
14
|
+
"connect",
|
|
15
|
+
2
|
|
16
|
+
]),
|
|
17
|
+
names: [
|
|
18
|
+
["ServiceInstance", "ServiceInstance"],
|
|
19
|
+
["OAuthApplication", "OAuthApplication"],
|
|
20
|
+
["OAuthConnection", "OAuthConnection"],
|
|
21
|
+
["OAuthAuthorizationAttempt", "OAuthAuthorizationAttempt"],
|
|
22
|
+
["ApiKeyConnection", "ApiKeyConnection"],
|
|
23
|
+
["ExternalSessionConnection", "ExternalSessionConnection"]
|
|
24
|
+
],
|
|
25
|
+
legacy: false
|
|
26
|
+
}, {
|
|
27
|
+
namespace: options.namespace,
|
|
28
|
+
names: [
|
|
29
|
+
["Installation", "ServiceInstance"],
|
|
30
|
+
["OAuthConnector", "OAuthApplication"],
|
|
31
|
+
["OAuthConnection", "OAuthConnection"],
|
|
32
|
+
["OAuthAuthorizationAttempt", "OAuthAuthorizationAttempt"]
|
|
33
|
+
],
|
|
34
|
+
legacy: true
|
|
35
|
+
}]) for (const [previous, current] of source.names) {
|
|
36
|
+
const table = Table.make({ name: JSON.stringify([
|
|
37
|
+
"ontology",
|
|
38
|
+
source.namespace,
|
|
39
|
+
"object",
|
|
40
|
+
previous
|
|
41
|
+
]) });
|
|
42
|
+
while (true) {
|
|
43
|
+
const batch = yield* options.tables.query(table, { limit: 100 });
|
|
44
|
+
yield* options.store.transaction(Effect.gen(function* () {
|
|
45
|
+
for (const { value } of batch) {
|
|
46
|
+
const id = value.id;
|
|
47
|
+
if (yield* options.store.get(current, id)) continue;
|
|
48
|
+
const { providerId, providerAppId, providerSubjectId, installation, connector, ...rest } = value;
|
|
49
|
+
const converted = source.legacy ? {
|
|
50
|
+
...rest,
|
|
51
|
+
...previous === "Installation" ? { service: providerId } : {},
|
|
52
|
+
...previous === "OAuthConnector" ? {
|
|
53
|
+
serviceInstance: installation,
|
|
54
|
+
serviceAppId: providerAppId
|
|
55
|
+
} : {},
|
|
56
|
+
...previous === "OAuthConnection" || previous === "OAuthAuthorizationAttempt" ? { application: connector } : {},
|
|
57
|
+
...previous === "OAuthConnection" ? { userId: providerSubjectId } : {}
|
|
58
|
+
} : value;
|
|
59
|
+
const decoded = yield* Schema.decodeUnknownEffect(schemas[current])(converted);
|
|
60
|
+
yield* options.store.put(current, decoded);
|
|
61
|
+
}
|
|
62
|
+
}));
|
|
63
|
+
yield* options.tables.transaction((tx) => Effect.forEach(batch, ({ key }) => tx.delete(table, key), { discard: true }));
|
|
64
|
+
if (batch.length < 100) break;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
//#endregion
|
|
69
|
+
export { migrateConnectCredentials };
|
|
70
|
+
|
|
71
|
+
//# sourceMappingURL=migrate.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migrate.js","names":[],"sources":["../../src/core/migrate.ts"],"sourcesContent":["import { compileEffectSchemas } from \"@party-stack/ontology-spec/effect\";\nimport { Table } from \"@party-stack/ontology-storage/tables\";\nimport { Effect, Schema } from \"effect\";\nimport type { ConnectStore } from \"./store.js\";\nimport type { OntologyIR } from \"@party-stack/ontology-spec\";\nimport type { TablesService } from \"@party-stack/ontology-storage/tables\";\n\n/** Import earlier Connect schemas without changing credential encryption AAD.\n * New commits precede old-row deletion. A crash can repeat a batch but cannot replace\n * an already imported/refreshed credential. Old journal cursors stay in the old namespace.\n */\nexport const migrateConnectCredentials = Effect.fn(\"Connect.migrate\")(function* (options: {\n tables: TablesService;\n namespace: string;\n ir: OntologyIR;\n store: ConnectStore;\n}) {\n const schemas = compileEffectSchemas(options.ir).objectSchemas;\n const legacyNames = [\n [\"Installation\", \"ServiceInstance\"],\n [\"OAuthConnector\", \"OAuthApplication\"],\n [\"OAuthConnection\", \"OAuthConnection\"],\n [\"OAuthAuthorizationAttempt\", \"OAuthAuthorizationAttempt\"],\n ] as const;\n const serviceNames = [\n [\"ServiceInstance\", \"ServiceInstance\"],\n [\"OAuthApplication\", \"OAuthApplication\"],\n [\"OAuthConnection\", \"OAuthConnection\"],\n [\"OAuthAuthorizationAttempt\", \"OAuthAuthorizationAttempt\"],\n [\"ApiKeyConnection\", \"ApiKeyConnection\"],\n [\"ExternalSessionConnection\", \"ExternalSessionConnection\"],\n ] as const;\n for (const source of [\n { namespace: JSON.stringify([options.namespace, \"connect\", 2]), names: serviceNames, legacy: false },\n { namespace: options.namespace, names: legacyNames, legacy: true },\n ]) {\n for (const [previous, current] of source.names) {\n const table = Table.make<Record<string, unknown>>({\n name: JSON.stringify([\"ontology\", source.namespace, \"object\", previous]),\n });\n while (true) {\n const batch = yield* options.tables.query(table, { limit: 100 });\n yield* options.store.transaction(\n Effect.gen(function* () {\n for (const { value } of batch) {\n const id = value.id as string;\n if (yield* options.store.get(current, id)) continue;\n const {\n providerId,\n providerAppId,\n providerSubjectId,\n installation,\n connector,\n ...rest\n } = value;\n const converted = source.legacy\n ? {\n ...rest,\n ...(previous === \"Installation\" ? { service: providerId } : {}),\n ...(previous === \"OAuthConnector\"\n ? { serviceInstance: installation, serviceAppId: providerAppId }\n : {}),\n ...(previous === \"OAuthConnection\" ||\n previous === \"OAuthAuthorizationAttempt\"\n ? { application: connector }\n : {}),\n ...(previous === \"OAuthConnection\"\n ? { userId: providerSubjectId }\n : {}),\n }\n : value;\n const decoded = yield* Schema.decodeUnknownEffect(schemas[current]!)(converted);\n yield* options.store.put(current, decoded as never);\n }\n })\n );\n yield* options.tables.transaction((tx) =>\n Effect.forEach(batch, ({ key }) => tx.delete(table, key), { discard: true })\n );\n if (batch.length < 100) break;\n }\n }\n }\n});\n"],"mappings":";;;;;;;;AAWA,MAAa,4BAA4B,OAAO,GAAG,iBAAiB,CAAC,CAAC,WAAW,SAK9E;CACC,MAAM,UAAU,qBAAqB,QAAQ,EAAE,CAAC,CAAC;CAejD,KAAK,MAAM,UAAU,CACjB;EAAE,WAAW,K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AAU,OAAO,OAAO,oBAAoB,QAAQ,QAAS,CAAC,CAAC,SAAS;KAC9E,OAAO,QAAQ,MAAM,IAAI,SAAS,OAAgB;IACtD;GACJ,CAAC,CACL;GACA,OAAO,QAAQ,OAAO,aAAa,OAC/B,OAAO,QAAQ,QAAQ,EAAE,UAAU,GAAG,OAAO,OAAO,GAAG,GAAG,EAAE,SAAS,KAAK,CAAC,CAC/E;GACA,IAAI,MAAM,SAAS,KAAK;EAC5B;CACJ;AAER,CAAC"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { ConnectError } from "./errors.js";
|
|
2
|
+
import { ConnectOAuthService } from "./oauthAuthority.js";
|
|
3
|
+
import { Effect, Redacted } from "effect";
|
|
4
|
+
import * as oauth from "oauth4webapi";
|
|
5
|
+
import { Temporal } from "temporal-polyfill";
|
|
6
|
+
//#region src/core/oauth.d.ts
|
|
7
|
+
export interface OAuthServiceOptions {
|
|
8
|
+
issuer: string;
|
|
9
|
+
authorizationEndpoint: string;
|
|
10
|
+
tokenEndpoint: string;
|
|
11
|
+
revocationEndpoint?: string;
|
|
12
|
+
clientId: string;
|
|
13
|
+
clientAuthentication: {
|
|
14
|
+
method: "none";
|
|
15
|
+
} | {
|
|
16
|
+
method: "client_secret_basic" | "client_secret_post";
|
|
17
|
+
secret: string | Redacted.Redacted<string>;
|
|
18
|
+
};
|
|
19
|
+
scopes: readonly string[];
|
|
20
|
+
resolveSubject(accessToken: string): Effect.Effect<string, ConnectError>;
|
|
21
|
+
/** Provider-specific metadata, when refresh expiration is actually reported. */
|
|
22
|
+
refreshTokenExpiry?(response: oauth.TokenEndpointResponse, receivedAt: number): Temporal.Instant | undefined;
|
|
23
|
+
fetch?: typeof globalThis.fetch;
|
|
24
|
+
}
|
|
25
|
+
export declare function makeOAuthService(options: OAuthServiceOptions): ConnectOAuthService;
|
|
26
|
+
//#endregion
|
|
27
|
+
//# sourceMappingURL=oauth.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauth.d.ts","names":["_$__errors_js0.ConnectError"],"sources":["../../src/core/oauth.ts"],"mappings":";;;;;;iBAMiB;EACb;EACA;EACA;EACA;EACA;EACA;IACQ;;IAEE;IACA,iBAAiB,SAAS;;EAEpC;EACA,eAAe,sBAAsB,OAAO,eAHRA;;EAKpC,oBACI,UAAU,MAAM,uBAChB,qBACD,SAAS;EACZ,eAAe,WAAW;;wBAGd,iBAAiB,SAAS,sBAAsB"}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { connectError } from "./errors.js";
|
|
2
|
+
import { Clock, Effect, Redacted } from "effect";
|
|
3
|
+
import * as oauth from "oauth4webapi";
|
|
4
|
+
import { Temporal } from "temporal-polyfill";
|
|
5
|
+
//#region src/core/oauth.ts
|
|
6
|
+
function makeOAuthService(options) {
|
|
7
|
+
const server = {
|
|
8
|
+
issuer: options.issuer,
|
|
9
|
+
authorization_endpoint: options.authorizationEndpoint,
|
|
10
|
+
token_endpoint: options.tokenEndpoint,
|
|
11
|
+
revocation_endpoint: options.revocationEndpoint
|
|
12
|
+
};
|
|
13
|
+
const client = { client_id: options.clientId };
|
|
14
|
+
const auth = options.clientAuthentication.method === "none" ? oauth.None() : options.clientAuthentication.method === "client_secret_basic" ? oauth.ClientSecretBasic(Redacted.isRedacted(options.clientAuthentication.secret) ? Redacted.value(options.clientAuthentication.secret) : options.clientAuthentication.secret) : oauth.ClientSecretPost(Redacted.isRedacted(options.clientAuthentication.secret) ? Redacted.value(options.clientAuthentication.secret) : options.clientAuthentication.secret);
|
|
15
|
+
const requestOptions = (signal) => ({
|
|
16
|
+
signal,
|
|
17
|
+
[oauth.customFetch]: options.fetch ?? globalThis.fetch.bind(globalThis)
|
|
18
|
+
});
|
|
19
|
+
const request = (run, refreshing = false) => Effect.gen(function* () {
|
|
20
|
+
const result = yield* Effect.tryPromise({
|
|
21
|
+
try: run,
|
|
22
|
+
catch: (error) => error instanceof oauth.ResponseBodyError && [
|
|
23
|
+
"invalid_grant",
|
|
24
|
+
"invalid_token",
|
|
25
|
+
"invalid_client"
|
|
26
|
+
].includes(error.error) ? connectError("NeedsAuthentication", "Provider credentials require authentication.") : refreshing && !(error instanceof oauth.ResponseBodyError) ? connectError("NeedsAuthentication", "Refresh outcome is unknown; reconnect before retrying.") : connectError("Provider", "OAuth oauth request failed.", error instanceof oauth.ResponseBodyError && error.status >= 500)
|
|
27
|
+
});
|
|
28
|
+
const now = yield* Clock.currentTimeMillis;
|
|
29
|
+
const userId = yield* options.resolveSubject(result.access_token).pipe(Effect.mapError((error) => refreshing ? connectError("NeedsAuthentication", "Could not verify refreshed credentials; reconnect before retrying.") : error));
|
|
30
|
+
return {
|
|
31
|
+
accessToken: result.access_token,
|
|
32
|
+
accessTokenExpiresAt: result.expires_in === void 0 ? void 0 : Temporal.Instant.fromEpochMilliseconds(now + result.expires_in * 1e3),
|
|
33
|
+
refreshToken: result.refresh_token,
|
|
34
|
+
refreshTokenExpiresAt: options.refreshTokenExpiry?.(result, now),
|
|
35
|
+
grantedScopes: result.scope,
|
|
36
|
+
userId
|
|
37
|
+
};
|
|
38
|
+
});
|
|
39
|
+
return {
|
|
40
|
+
authorizationUrl: (input) => Effect.try({
|
|
41
|
+
try: () => {
|
|
42
|
+
const url = new URL(options.authorizationEndpoint);
|
|
43
|
+
url.search = new URLSearchParams({
|
|
44
|
+
client_id: options.clientId,
|
|
45
|
+
response_type: "code",
|
|
46
|
+
redirect_uri: input.redirectUrl,
|
|
47
|
+
state: input.state,
|
|
48
|
+
code_challenge: input.codeChallenge,
|
|
49
|
+
code_challenge_method: "S256",
|
|
50
|
+
scope: options.scopes.join(" ")
|
|
51
|
+
}).toString();
|
|
52
|
+
return url.href;
|
|
53
|
+
},
|
|
54
|
+
catch: () => connectError("Configuration", "OAuth authorization endpoint is invalid.")
|
|
55
|
+
}),
|
|
56
|
+
exchange: (input) => request(async (signal) => {
|
|
57
|
+
const parameters = oauth.validateAuthResponse(server, client, new URL(input.callbackUrl).searchParams, input.state);
|
|
58
|
+
const response = await oauth.authorizationCodeGrantRequest(server, client, auth, parameters, input.redirectUrl, input.codeVerifier, requestOptions(signal));
|
|
59
|
+
return oauth.processAuthorizationCodeResponse(server, client, response);
|
|
60
|
+
}),
|
|
61
|
+
refresh: (token) => request(async (signal) => {
|
|
62
|
+
const response = await oauth.refreshTokenGrantRequest(server, client, auth, token, requestOptions(signal));
|
|
63
|
+
return oauth.processRefreshTokenResponse(server, client, response);
|
|
64
|
+
}, true),
|
|
65
|
+
clientCredentials: request(async (signal) => {
|
|
66
|
+
const response = await oauth.clientCredentialsGrantRequest(server, client, auth, { scope: options.scopes.join(" ") }, requestOptions(signal));
|
|
67
|
+
return oauth.processClientCredentialsResponse(server, client, response);
|
|
68
|
+
}),
|
|
69
|
+
revoke: (token) => Effect.tryPromise({
|
|
70
|
+
try: async (signal) => {
|
|
71
|
+
if (!options.revocationEndpoint) return;
|
|
72
|
+
const response = await oauth.revocationRequest(server, client, auth, token, requestOptions(signal));
|
|
73
|
+
await oauth.processRevocationResponse(response);
|
|
74
|
+
},
|
|
75
|
+
catch: () => connectError("Provider", "Provider token revocation failed.", true)
|
|
76
|
+
})
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
//#endregion
|
|
80
|
+
export { makeOAuthService };
|
|
81
|
+
|
|
82
|
+
//# sourceMappingURL=oauth.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauth.js","names":[],"sources":["../../src/core/oauth.ts"],"sourcesContent":["import { Clock, Effect, Redacted } from \"effect\";\nimport * as oauth from \"oauth4webapi\";\nimport { Temporal } from \"temporal-polyfill\";\nimport { connectError } from \"./errors.js\";\nimport type { ConnectOAuthService, OAuthTokens } from \"./oauthAuthority.js\";\n\nexport interface OAuthServiceOptions {\n issuer: string;\n authorizationEndpoint: string;\n tokenEndpoint: string;\n revocationEndpoint?: string;\n clientId: string;\n clientAuthentication:\n | { method: \"none\" }\n | {\n method: \"client_secret_basic\" | \"client_secret_post\";\n secret: string | Redacted.Redacted<string>;\n };\n scopes: readonly string[];\n resolveSubject(accessToken: string): Effect.Effect<string, import(\"./errors.js\").ConnectError>;\n /** Provider-specific metadata, when refresh expiration is actually reported. */\n refreshTokenExpiry?(\n response: oauth.TokenEndpointResponse,\n receivedAt: number\n ): Temporal.Instant | undefined;\n fetch?: typeof globalThis.fetch;\n}\n\nexport function makeOAuthService(options: OAuthServiceOptions): ConnectOAuthService {\n const server: oauth.AuthorizationServer = {\n issuer: options.issuer,\n authorization_endpoint: options.authorizationEndpoint,\n token_endpoint: options.tokenEndpoint,\n revocation_endpoint: options.revocationEndpoint,\n };\n const client: oauth.Client = { client_id: options.clientId };\n const auth =\n options.clientAuthentication.method === \"none\"\n ? oauth.None()\n : options.clientAuthentication.method === \"client_secret_basic\"\n ? oauth.ClientSecretBasic(\n Redacted.isRedacted(options.clientAuthentication.secret)\n ? Redacted.value(options.clientAuthentication.secret)\n : options.clientAuthentication.secret\n )\n : oauth.ClientSecretPost(\n Redacted.isRedacted(options.clientAuthentication.secret)\n ? Redacted.value(options.clientAuthentication.secret)\n : options.clientAuthentication.secret\n );\n const requestOptions = (signal: AbortSignal) => ({\n signal,\n [oauth.customFetch]: options.fetch ?? globalThis.fetch.bind(globalThis),\n });\n const request = (\n run: (signal: AbortSignal) => Promise<oauth.TokenEndpointResponse>,\n refreshing = false\n ) =>\n Effect.gen(function* () {\n const result = yield* Effect.tryPromise({\n try: run,\n catch: (error) =>\n error instanceof oauth.ResponseBodyError &&\n [\"invalid_grant\", \"invalid_token\", \"invalid_client\"].includes(error.error)\n ? connectError(\"NeedsAuthentication\", \"Provider credentials require authentication.\")\n : refreshing && !(error instanceof oauth.ResponseBodyError)\n ? connectError(\n \"NeedsAuthentication\",\n \"Refresh outcome is unknown; reconnect before retrying.\"\n )\n : connectError(\n \"Provider\",\n \"OAuth oauth request failed.\",\n error instanceof oauth.ResponseBodyError && error.status >= 500\n ),\n });\n const now = yield* Clock.currentTimeMillis;\n const userId = yield* options\n .resolveSubject(result.access_token)\n .pipe(\n Effect.mapError((error) =>\n refreshing\n ? connectError(\n \"NeedsAuthentication\",\n \"Could not verify refreshed credentials; reconnect before retrying.\"\n )\n : error\n )\n );\n return {\n accessToken: result.access_token,\n accessTokenExpiresAt:\n result.expires_in === undefined\n ? undefined\n : Temporal.Instant.fromEpochMilliseconds(now + result.expires_in * 1000),\n refreshToken: result.refresh_token,\n refreshTokenExpiresAt: options.refreshTokenExpiry?.(result, now),\n grantedScopes: result.scope,\n userId,\n } satisfies OAuthTokens;\n });\n return {\n authorizationUrl: (input) =>\n Effect.try({\n try: () => {\n const url = new URL(options.authorizationEndpoint);\n url.search = new URLSearchParams({\n client_id: options.clientId,\n response_type: \"code\",\n redirect_uri: input.redirectUrl,\n state: input.state,\n code_challenge: input.codeChallenge,\n code_challenge_method: \"S256\",\n scope: options.scopes.join(\" \"),\n }).toString();\n return url.href;\n },\n catch: () => connectError(\"Configuration\", \"OAuth authorization endpoint is invalid.\"),\n }),\n exchange: (input) =>\n request(async (signal) => {\n const parameters = oauth.validateAuthResponse(\n server,\n client,\n new URL(input.callbackUrl).searchParams,\n input.state\n );\n const response = await oauth.authorizationCodeGrantRequest(\n server,\n client,\n auth,\n parameters,\n input.redirectUrl,\n input.codeVerifier,\n requestOptions(signal)\n );\n return oauth.processAuthorizationCodeResponse(server, client, response);\n }),\n refresh: (token) =>\n request(async (signal) => {\n const response = await oauth.refreshTokenGrantRequest(\n server,\n client,\n auth,\n token,\n requestOptions(signal)\n );\n return oauth.processRefreshTokenResponse(server, client, response);\n }, true),\n clientCredentials: request(async (signal) => {\n const response = await oauth.clientCredentialsGrantRequest(\n server,\n client,\n auth,\n { scope: options.scopes.join(\" \") },\n requestOptions(signal)\n );\n return oauth.processClientCredentialsResponse(server, client, response);\n }),\n revoke: (token) =>\n Effect.tryPromise({\n try: async (signal) => {\n if (!options.revocationEndpoint) return;\n const response = await oauth.revocationRequest(\n server,\n client,\n auth,\n token,\n requestOptions(signal)\n );\n await oauth.processRevocationResponse(response);\n },\n catch: () => connectError(\"Provider\", \"Provider token revocation failed.\", true),\n }),\n };\n}\n"],"mappings":";;;;;AA4BA,SAAgB,iBAAiB,SAAmD;CAChF,MAAM,SAAoC;EACtC,QAAQ,QAAQ;EAChB,wBAAwB,QAAQ;EAChC,gBAAgB,QAAQ;EACxB,qBAAqB,QAAQ;CACjC;CACA,MAAM,SAAuB,EAAE,WAAW,QAAQ,SAAS;CAC3D,MAAM,OACF,QAAQ,qBAAqB,WAAW,SAClC,MAAM,KAAK,IACX,QAAQ,qBAAqB,WAAW,wBACtC,MAAM,kBACF,SAAS,WAAW,QAAQ,qBAAqB,MAAM,IACjD,SAAS,MAAM,QAAQ,qBAAqB,MAAM,IAClD,QAAQ,qBAAqB,MACvC,IACA,MAAM,iBACF,SAAS,WAAW,QAAQ,qBAAqB,MAAM,IACjD,SAAS,MAAM,QAAQ,qBAAqB,MAAM,IAClD,QAAQ,qBAAqB,MACvC;CACZ,MAAM,kBAAkB,YAAyB;EAC7C;GACC,MAAM,cAAc,QAAQ,SAAS,WAAW,MAAM,KAAK,UAAU;CAC1E;CACA,MAAM,WACF,KACA,aAAa,UAEb,OAAO,IAAI,aAAa;EACpB,MAAM,SAAS,OAAO,OAAO,WAAW;GACpC,KAAK;GACL,QAAQ,UACJ,iBAAiB,MAAM,qBACvB;IAAC;IAAiB;IAAiB;GAAgB,CAAC,CAAC,SAAS,MAAM,KAAK,IACnE,aAAa,uBAAuB,8CAA8C,IAClF,cAAc,EAAE,iBAAiB,MAAM,qBACrC,aACI,uBACA,wDACJ,IACA,aACI,YACA,+BACA,iBAAiB,MAAM,qBAAqB,MAAM,UAAU,GAChE;EAChB,CAAC;EACD,MAAM,MAAM,OAAO,MAAM;EACzB,MAAM,SAAS,OAAO,QACjB,eAAe,OAAO,YAAY,CAAC,CACnC,KACG,OAAO,UAAU,UACb,aACM,aACI,uBACA,oEACJ,IACA,KACV,CACJ;EACJ,OAAO;GAC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AQ;EAC1E,CAAC;EACD,SAAS,UACL,OAAO,WAAW;GACd,KAAK,OAAO,WAAW;IACnB,IAAI,CAAC,QAAQ,oBAAoB;IACjC,MAAM,WAAW,MAAM,MAAM,kBACzB,QACA,QACA,MACA,OACA,eAAe,MAAM,CACzB;IACA,MAAM,MAAM,0BAA0B,QAAQ;GAClD;GACA,aAAa,aAAa,YAAY,qCAAqC,IAAI;EACnF,CAAC;CACT;AACJ"}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { ConnectError } from "./errors.js";
|
|
2
|
+
import { OAuthApplicationRecord, OAuthAuthorizationAttemptRecord, OAuthConnectionRecord, ServiceInstanceRecord } from "../spec/index.js";
|
|
3
|
+
import { ConnectStore } from "./store.js";
|
|
4
|
+
import { Context, Effect, Layer, Schema } from "effect";
|
|
5
|
+
import { Temporal } from "temporal-polyfill";
|
|
6
|
+
import { Encrypted } from "@party-stack/ontology-spec/values";
|
|
7
|
+
//#region src/core/oauthAuthority.d.ts
|
|
8
|
+
export interface OAuthTokens {
|
|
9
|
+
accessToken: string;
|
|
10
|
+
accessTokenExpiresAt?: Temporal.Instant;
|
|
11
|
+
refreshToken?: string;
|
|
12
|
+
refreshTokenExpiresAt?: Temporal.Instant;
|
|
13
|
+
grantedScopes?: string;
|
|
14
|
+
userId: string;
|
|
15
|
+
}
|
|
16
|
+
export interface ConnectOAuthService {
|
|
17
|
+
authorizationUrl(input: {
|
|
18
|
+
state: string;
|
|
19
|
+
codeChallenge: string;
|
|
20
|
+
redirectUrl: string;
|
|
21
|
+
}): Effect.Effect<string, ConnectError>;
|
|
22
|
+
exchange(input: {
|
|
23
|
+
callbackUrl: string;
|
|
24
|
+
state: string;
|
|
25
|
+
codeVerifier: string;
|
|
26
|
+
redirectUrl: string;
|
|
27
|
+
}): Effect.Effect<OAuthTokens, ConnectError>;
|
|
28
|
+
refresh(refreshToken: string): Effect.Effect<OAuthTokens, ConnectError>;
|
|
29
|
+
clientCredentials: Effect.Effect<OAuthTokens, ConnectError>;
|
|
30
|
+
revoke?(token: string): Effect.Effect<void, ConnectError>;
|
|
31
|
+
}
|
|
32
|
+
export interface BeginAuthorization {
|
|
33
|
+
applicationId: string;
|
|
34
|
+
principalId?: string;
|
|
35
|
+
redirectUrl: string;
|
|
36
|
+
returnUrl?: string;
|
|
37
|
+
connectionId?: string;
|
|
38
|
+
/** Trusted application fields; reserved attempt fields always take precedence. */
|
|
39
|
+
properties?: Record<string, unknown>;
|
|
40
|
+
}
|
|
41
|
+
export interface OAuthAuthorityService {
|
|
42
|
+
connectionForApplication(applicationId: string): Effect.Effect<OAuthConnectionRecord | undefined, ConnectError>;
|
|
43
|
+
begin(input: BeginAuthorization): Effect.Effect<{
|
|
44
|
+
id: string;
|
|
45
|
+
authorizationUrl: string;
|
|
46
|
+
}, ConnectError>;
|
|
47
|
+
complete(input: {
|
|
48
|
+
callbackUrl: string;
|
|
49
|
+
principalId?: string;
|
|
50
|
+
}): Effect.Effect<OAuthConnectionRecord, ConnectError>;
|
|
51
|
+
clientCredentials(input: {
|
|
52
|
+
applicationId: string;
|
|
53
|
+
connectionId?: string;
|
|
54
|
+
properties?: Record<string, unknown>;
|
|
55
|
+
}): Effect.Effect<OAuthConnectionRecord, ConnectError>;
|
|
56
|
+
refresh(connectionId: string): Effect.Effect<OAuthConnectionRecord, ConnectError>;
|
|
57
|
+
disconnect(connectionId: string): Effect.Effect<void, ConnectError>;
|
|
58
|
+
forget(connectionId: string): Effect.Effect<void, ConnectError>;
|
|
59
|
+
/** Indexed, bounded maintenance. Does not delete connection identities. */
|
|
60
|
+
collectExpired(options?: {
|
|
61
|
+
limit?: number;
|
|
62
|
+
}): Effect.Effect<{
|
|
63
|
+
attempts: number;
|
|
64
|
+
refreshTokens: number;
|
|
65
|
+
}, ConnectError>;
|
|
66
|
+
}
|
|
67
|
+
export interface ConnectCredentialValues {
|
|
68
|
+
encrypt<A, AI>(schema: Schema.Codec<A, AI>, value: A): Effect.Effect<Encrypted<A>, unknown>;
|
|
69
|
+
decrypt<A, AI>(schema: Schema.Codec<A, AI>, value: Encrypted<A>): Effect.Effect<A, unknown>;
|
|
70
|
+
evict(value: Encrypted<unknown>): Effect.Effect<void, unknown>;
|
|
71
|
+
}
|
|
72
|
+
export interface OAuthAuthorityOptions {
|
|
73
|
+
store: ConnectStore;
|
|
74
|
+
values: ConnectCredentialValues;
|
|
75
|
+
oauth(input: {
|
|
76
|
+
application: OAuthApplicationRecord;
|
|
77
|
+
serviceInstance: ServiceInstanceRecord;
|
|
78
|
+
}): Effect.Effect<ConnectOAuthService, ConnectError>;
|
|
79
|
+
/** Populate application ownership properties in the same commit as token storage. */
|
|
80
|
+
connectionProperties?(attempt: OAuthAuthorizationAttemptRecord): Effect.Effect<Record<string, unknown>, ConnectError>;
|
|
81
|
+
}
|
|
82
|
+
declare const OAuthAuthority_base: Context.ServiceClass<OAuthAuthority, "@party-stack/connect/OAuthAuthority", OAuthAuthorityService>;
|
|
83
|
+
export declare class OAuthAuthority extends OAuthAuthority_base {
|
|
84
|
+
static readonly layer: (options: OAuthAuthorityOptions) => Layer.Layer<OAuthAuthority, never, never>;
|
|
85
|
+
}
|
|
86
|
+
/** One credential authority, usable by both device and HTTP entry points. */
|
|
87
|
+
export declare const makeOAuthAuthority: (options: OAuthAuthorityOptions) => Effect.Effect<OAuthAuthorityService>;
|
|
88
|
+
//#endregion
|
|
89
|
+
export {};
|
|
90
|
+
//# sourceMappingURL=oauthAuthority.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauthAuthority.d.ts","names":[],"sources":["../../src/core/oauthAuthority.ts"],"mappings":";;;;;;;iBAciB;EACb;EACA,uBAAuB,SAAS;EAChC;EACA,wBAAwB,SAAS;EACjC;EACA;;iBAEa;EACb,iBAAiB;IACb;IACA;IACA;MACA,OAAO,eAAe;EAC1B,SAAS;IACL;IACA;IACA;IACA;MACA,OAAO,OAAO,aAAa;EAC/B,QAAQ,uBAAuB,OAAO,OAAO,aA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