@party-stack/connect 0.4.2 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/core/migrate.d.ts.map +1 -1
- package/lib/core/migrate.js +39 -25
- package/lib/core/migrate.js.map +1 -1
- package/lib/core/oauth.js +2 -2
- package/lib/core/oauth.js.map +1 -1
- package/lib/core/oauthAuthority.js +29 -23
- package/lib/core/oauthAuthority.js.map +1 -1
- package/lib/core/store.d.ts.map +1 -1
- package/lib/core/store.js +1 -1
- package/lib/core/store.js.map +1 -1
- package/lib/serviceConnections.d.ts.map +1 -1
- package/lib/serviceConnections.js +15 -6
- package/lib/serviceConnections.js.map +1 -1
- package/lib/spec/index.d.ts +39 -0
- package/lib/spec/index.d.ts.map +1 -1
- package/lib/spec/index.js +18 -0
- package/lib/spec/index.js.map +1 -1
- package/package.json +5 -5
|
@@ -1 +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;
|
|
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;MAsET,OAAA,aAtESA,8DAsET,uBAAA,OAAA"}
|
package/lib/core/migrate.js
CHANGED
|
@@ -8,31 +8,45 @@ import { Table } from "@party-stack/ontology-storage/tables";
|
|
|
8
8
|
*/
|
|
9
9
|
const migrateConnectCredentials = Effect.fn("Connect.migrate")(function* (options) {
|
|
10
10
|
const schemas = compileEffectSchemas(options.ir).objectSchemas;
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
11
|
+
const legacyNames = [
|
|
12
|
+
["Installation", "ServiceInstance"],
|
|
13
|
+
["OAuthConnector", "OAuthApplication"],
|
|
14
|
+
["OAuthConnection", "OAuthConnection"],
|
|
15
|
+
["OAuthAuthorizationAttempt", "OAuthAuthorizationAttempt"]
|
|
16
|
+
];
|
|
17
|
+
const serviceNames = [
|
|
18
|
+
["ServiceInstance", "ServiceInstance"],
|
|
19
|
+
["OAuthApplication", "OAuthApplication"],
|
|
20
|
+
["OAuthConnection", "OAuthConnection"],
|
|
21
|
+
["OAuthAuthorizationAttempt", "OAuthAuthorizationAttempt"],
|
|
22
|
+
["ApiKeyConnection", "ApiKeyConnection"],
|
|
23
|
+
["ExternalSessionConnection", "ExternalSessionConnection"]
|
|
24
|
+
];
|
|
25
|
+
for (const source of [
|
|
26
|
+
{
|
|
27
|
+
namespace: JSON.stringify([
|
|
28
|
+
options.namespace,
|
|
29
|
+
"connect",
|
|
30
|
+
3
|
|
31
|
+
]),
|
|
32
|
+
names: serviceNames,
|
|
33
|
+
legacy: false
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
namespace: JSON.stringify([
|
|
37
|
+
options.namespace,
|
|
38
|
+
"connect",
|
|
39
|
+
2
|
|
40
|
+
]),
|
|
41
|
+
names: serviceNames,
|
|
42
|
+
legacy: false
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
namespace: options.namespace,
|
|
46
|
+
names: legacyNames,
|
|
47
|
+
legacy: true
|
|
48
|
+
}
|
|
49
|
+
]) for (const [previous, current] of source.names) {
|
|
36
50
|
const table = Table.make({ name: JSON.stringify([
|
|
37
51
|
"ontology",
|
|
38
52
|
source.namespace,
|
package/lib/core/migrate.js.map
CHANGED
|
@@ -1 +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;
|
|
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 // Version 4 only adds optional properties, so version 3 rows import unchanged.\n { namespace: JSON.stringify([options.namespace, \"connect\", 3]), names: serviceNames, legacy: false },\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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ACA,mBACA,cACA,WACA,GAAG,SACH;KACJ,MAAM,YAAY,OAAO,SACnB;MACI,GAAG;MACH,GAAI,aAAa,iBAAiB,EAAE,SAAS,WAAW,IAAI,CAAC;MAC7D,GAAI,aAAa,mBACX;OAAE,iBAAiB;OAAc,cAAc;MAAc,IAC7D,CAAC;MACP,GAAI,aAAa,qBACjB,aAAa,8BACP,EAAE,aAAa,UAAU,IACzB,CAAC;MACP,GAAI,aAAa,oBACX,EAAE,QAAQ,kBAAkB,IAC5B,CAAC;KACX,IACA;KACN,MAAM,UAAU,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"}
|
package/lib/core/oauth.js
CHANGED
|
@@ -23,10 +23,10 @@ function makeOAuthService(options) {
|
|
|
23
23
|
"invalid_grant",
|
|
24
24
|
"invalid_token",
|
|
25
25
|
"invalid_client"
|
|
26
|
-
].includes(error.error) ? connectError("NeedsAuthentication",
|
|
26
|
+
].includes(error.error) ? connectError("NeedsAuthentication", `The provider rejected the saved credentials (${error.error}).`) : connectError("Provider", error instanceof oauth.ResponseBodyError ? "OAuth request failed." : "Could not reach the provider.", !(error instanceof oauth.ResponseBodyError) || error.status >= 500)
|
|
27
27
|
});
|
|
28
28
|
const now = yield* Clock.currentTimeMillis;
|
|
29
|
-
const userId = yield* options.resolveSubject(result.access_token).pipe(Effect.mapError((error) => refreshing ? connectError("
|
|
29
|
+
const userId = yield* options.resolveSubject(result.access_token).pipe(Effect.mapError((error) => refreshing && error.kind !== "NeedsAuthentication" ? connectError("Provider", "Could not verify refreshed credentials.", true) : error));
|
|
30
30
|
return {
|
|
31
31
|
accessToken: result.access_token,
|
|
32
32
|
accessTokenExpiresAt: result.expires_in === void 0 ? void 0 : Temporal.Instant.fromEpochMilliseconds(now + result.expires_in * 1e3),
|
package/lib/core/oauth.js.map
CHANGED
|
@@ -1 +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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AC3B,MAAM,KACV;GACA,MAAM,WAAW,MAAM,MAAM,8BACzB,QACA,QACA,MACA,YACA,MAAM,aACN,MAAM,cACN,eAAe,MAAM,CACzB;GACA,OAAO,MAAM,iCAAiC,QAAQ,QAAQ,QAAQ;EAC1E,CAAC;EACL,UAAU,UACN,QAAQ,OAAO,WAAW;GACtB,MAAM,WAAW,MAAM,MAAM,yBACzB,QACA,QACA,MACA,OACA,eAAe,MAAM,CACzB;GACA,OAAO,MAAM,4BAA4B,QAAQ,QAAQ,QAAQ;EACrE,GAAG,IAAI;EACX,mBAAmB,QAAQ,OAAO,WAAW;GACzC,MAAM,WAAW,MAAM,MAAM,8BACzB,QACA,QACA,MACA,EAAE,OAAO,QAAQ,OAAO,KAAK,GAAG,EAAE,GAClC,eAAe,MAAM,CACzB;GACA,OAAO,MAAM,iCAAiC,QAAQ,QAAQ,QAAQ;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"}
|
|
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 // Only the provider's rejection asks for a sign-in. A request that never got an\n // answer (offline, a dropped connection) keeps the saved credentials: retrying a\n // refresh is never worse than asking for a sign-in, since a provider that refuses\n // a reused refresh token answers `invalid_grant` and asks for one then.\n catch: (error) =>\n error instanceof oauth.ResponseBodyError &&\n [\"invalid_grant\", \"invalid_token\", \"invalid_client\"].includes(error.error)\n ? connectError(\n \"NeedsAuthentication\",\n `The provider rejected the saved credentials (${error.error}).`\n )\n : connectError(\n \"Provider\",\n error instanceof oauth.ResponseBodyError\n ? \"OAuth request failed.\"\n : \"Could not reach the provider.\",\n !(error instanceof oauth.ResponseBodyError) || error.status >= 500\n ),\n });\n const now = yield* Clock.currentTimeMillis;\n const userId = yield* options.resolveSubject(result.access_token).pipe(\n // The refreshed tokens are dropped; the saved refresh token is tried again later.\n Effect.mapError((error) =>\n refreshing && error.kind !== \"NeedsAuthentication\"\n ? connectError(\"Provider\", \"Could not verify refreshed credentials.\", true)\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;GAKL,QAAQ,UACJ,iBAAiB,MAAM,qBACvB;IAAC;IAAiB;IAAiB;GAAgB,CAAC,CAAC,SAAS,MAAM,KAAK,IACnE,aACI,uBACA,gDAAgD,MAAM,MAAM,GAChE,IACA,aACI,YACA,iBAAiB,MAAM,oBACjB,0BACA,iCACN,EAAE,iBAAiB,MAAM,sBAAsB,MAAM,UAAU,GACnE;EACd,CAAC;EACD,MAAM,MAAM,OAAO,MAAM;EACzB,MAAM,SAAS,OAAO,QAAQ,eAAe,OAAO,YAAY,CAAC,CAAC,KAE9D,OA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AAQ,OAAO,KAAK,GAAG,EAAE,GAClC,eAAe,MAAM,CACzB;GACA,OAAO,MAAM,iCAAiC,QAAQ,QAAQ,QAAQ;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"}
|
|
@@ -85,6 +85,7 @@ const makeOAuthAuthority = (options) => Effect.sync(() => {
|
|
|
85
85
|
const next = {
|
|
86
86
|
...record,
|
|
87
87
|
status: "active",
|
|
88
|
+
statusReason: void 0,
|
|
88
89
|
userId: tokens.userId,
|
|
89
90
|
accessToken: yield* encrypt(tokens.accessToken),
|
|
90
91
|
accessTokenExpiresAt: tokens.accessTokenExpiresAt,
|
|
@@ -115,21 +116,7 @@ const makeOAuthAuthority = (options) => Effect.sync(() => {
|
|
|
115
116
|
const operationId = crypto.randomUUID();
|
|
116
117
|
const record = yield* store.transaction(Effect.gen(function* () {
|
|
117
118
|
const current = yield* read(connectionId);
|
|
118
|
-
if (current.operationId)
|
|
119
|
-
if (!expired(current.operationExpiresAt, yield* Clock.currentTimeMillis)) return yield* connectError("Busy", "Connection operation is in progress.", true);
|
|
120
|
-
if ((yield* store.get("OAuthApplication", current.application))?.flow !== "client-credentials") {
|
|
121
|
-
yield* evict(current.refreshToken);
|
|
122
|
-
yield* store.put("OAuthConnection", {
|
|
123
|
-
...current,
|
|
124
|
-
status: "needs-auth",
|
|
125
|
-
refreshToken: void 0,
|
|
126
|
-
refreshTokenExpiresAt: void 0,
|
|
127
|
-
operationId: void 0,
|
|
128
|
-
operationExpiresAt: void 0
|
|
129
|
-
});
|
|
130
|
-
return;
|
|
131
|
-
}
|
|
132
|
-
}
|
|
119
|
+
if (current.operationId && !expired(current.operationExpiresAt, yield* Clock.currentTimeMillis)) return yield* connectError("Busy", "Connection operation is in progress.", true);
|
|
133
120
|
if (current.status !== "active") return yield* connectError("NeedsAuthentication", "Reconnect this connection.");
|
|
134
121
|
const next = {
|
|
135
122
|
...current,
|
|
@@ -139,7 +126,6 @@ const makeOAuthAuthority = (options) => Effect.sync(() => {
|
|
|
139
126
|
yield* store.put("OAuthConnection", next);
|
|
140
127
|
return next;
|
|
141
128
|
}));
|
|
142
|
-
if (!record) return yield* connectError("NeedsAuthentication", "An interrupted credential operation requires reconnection.");
|
|
143
129
|
return yield* Effect.gen(function* () {
|
|
144
130
|
const { application, oauth } = yield* configured(record.application);
|
|
145
131
|
let tokens;
|
|
@@ -157,7 +143,7 @@ const makeOAuthAuthority = (options) => Effect.sync(() => {
|
|
|
157
143
|
const current = yield* finish(record, operationId);
|
|
158
144
|
return yield* saveTokens(current, tokens);
|
|
159
145
|
}));
|
|
160
|
-
}).pipe(Effect.timeout(45e3), Effect.catchTag("TimeoutError", () => Effect.fail(connectError("
|
|
146
|
+
}).pipe(Effect.timeout(45e3), Effect.catchTag("TimeoutError", () => Effect.fail(connectError("Provider", "Credential exchange timed out.", true)))).pipe(Effect.catch((error) => store.transaction(Effect.gen(function* () {
|
|
161
147
|
const current = yield* finish(record, operationId);
|
|
162
148
|
if (error.kind === "NeedsAuthentication") {
|
|
163
149
|
yield* evict(current.refreshToken);
|
|
@@ -166,6 +152,7 @@ const makeOAuthAuthority = (options) => Effect.sync(() => {
|
|
|
166
152
|
refreshToken: void 0,
|
|
167
153
|
refreshTokenExpiresAt: void 0,
|
|
168
154
|
status: "needs-auth",
|
|
155
|
+
statusReason: error.message,
|
|
169
156
|
operationId: void 0,
|
|
170
157
|
operationExpiresAt: void 0
|
|
171
158
|
});
|
|
@@ -174,7 +161,13 @@ const makeOAuthAuthority = (options) => Effect.sync(() => {
|
|
|
174
161
|
operationId: void 0,
|
|
175
162
|
operationExpiresAt: void 0
|
|
176
163
|
});
|
|
177
|
-
})).pipe(Effect.andThen(Effect.
|
|
164
|
+
})).pipe(Effect.andThen(error.kind === "NeedsAuthentication" ? Effect.logWarning("Connection needs a sign-in", {
|
|
165
|
+
connection: record.id,
|
|
166
|
+
reason: error.message
|
|
167
|
+
}) : Effect.logWarning("Connection refresh failed; keeping the session", {
|
|
168
|
+
connection: record.id,
|
|
169
|
+
reason: error.message
|
|
170
|
+
})), Effect.andThen(Effect.fail(error)))));
|
|
178
171
|
});
|
|
179
172
|
return OAuthAuthority.of({
|
|
180
173
|
connectionForApplication: Effect.fn("Connect.connectionForApplication")(function* (applicationId) {
|
|
@@ -317,6 +310,7 @@ const makeOAuthAuthority = (options) => Effect.sync(() => {
|
|
|
317
310
|
title: existing?.title ?? application.title,
|
|
318
311
|
application: application.id,
|
|
319
312
|
status: "active",
|
|
313
|
+
statusReason: void 0,
|
|
320
314
|
operationId: void 0,
|
|
321
315
|
operationExpiresAt: void 0
|
|
322
316
|
});
|
|
@@ -421,7 +415,12 @@ const makeOAuthAuthority = (options) => Effect.sync(() => {
|
|
|
421
415
|
...record,
|
|
422
416
|
refreshToken: void 0,
|
|
423
417
|
refreshTokenExpiresAt: void 0,
|
|
424
|
-
status: "needs-auth"
|
|
418
|
+
status: "needs-auth",
|
|
419
|
+
statusReason: "The saved refresh token expired."
|
|
420
|
+
});
|
|
421
|
+
yield* Effect.logWarning("Connection needs a sign-in", {
|
|
422
|
+
connection: record.id,
|
|
423
|
+
reason: "The saved refresh token expired."
|
|
425
424
|
});
|
|
426
425
|
}
|
|
427
426
|
const expiredConnections = yield* store.load("ApiKeyConnection", {
|
|
@@ -429,10 +428,17 @@ const makeOAuthAuthority = (options) => Effect.sync(() => {
|
|
|
429
428
|
orderBy: [{ field: field("expiresAt") }],
|
|
430
429
|
limit
|
|
431
430
|
});
|
|
432
|
-
for (const record of expiredConnections)
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
431
|
+
for (const record of expiredConnections) {
|
|
432
|
+
yield* store.put("ApiKeyConnection", {
|
|
433
|
+
...record,
|
|
434
|
+
status: "needs-auth",
|
|
435
|
+
statusReason: "The API key expired."
|
|
436
|
+
});
|
|
437
|
+
yield* Effect.logWarning("Connection needs a sign-in", {
|
|
438
|
+
connection: record.id,
|
|
439
|
+
reason: "The API key expired."
|
|
440
|
+
});
|
|
441
|
+
}
|
|
436
442
|
return {
|
|
437
443
|
attempts: attempts.length,
|
|
438
444
|
refreshTokens: connections.length
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauthAuthority.js","names":[],"sources":["../../src/core/oauthAuthority.ts"],"sourcesContent":["import { and, eq, field, lte, ne } from \"@party-stack/ontology-storage\";\nimport { Clock, Context, Effect, Layer, Schema, Redacted } from \"effect\";\nimport * as oauth4webapi from \"oauth4webapi\";\nimport { Temporal } from \"temporal-polyfill\";\nimport { connectError, type ConnectError } from \"./errors.js\";\nimport type {\n ServiceInstanceRecord,\n OAuthAuthorizationAttemptRecord,\n OAuthConnectionRecord,\n OAuthApplicationRecord,\n} from \"../spec/index.js\";\nimport type { ConnectStore } from \"./store.js\";\nimport type { Encrypted } from \"@party-stack/ontology-spec/values\";\n\nexport interface OAuthTokens {\n accessToken: string;\n accessTokenExpiresAt?: Temporal.Instant;\n refreshToken?: string;\n refreshTokenExpiresAt?: Temporal.Instant;\n grantedScopes?: string;\n userId: string;\n}\nexport interface ConnectOAuthService {\n authorizationUrl(input: {\n state: string;\n codeChallenge: string;\n redirectUrl: string;\n }): Effect.Effect<string, ConnectError>;\n exchange(input: {\n callbackUrl: string;\n state: string;\n codeVerifier: string;\n redirectUrl: string;\n }): Effect.Effect<OAuthTokens, ConnectError>;\n refresh(refreshToken: string): Effect.Effect<OAuthTokens, ConnectError>;\n clientCredentials: Effect.Effect<OAuthTokens, ConnectError>;\n revoke?(token: string): Effect.Effect<void, ConnectError>;\n}\nexport interface BeginAuthorization {\n applicationId: string;\n principalId?: string;\n redirectUrl: string;\n returnUrl?: string;\n connectionId?: string;\n /** Trusted application fields; reserved attempt fields always take precedence. */\n properties?: Record<string, unknown>;\n}\nexport interface OAuthAuthorityService {\n connectionForApplication(\n applicationId: string\n ): Effect.Effect<OAuthConnectionRecord | undefined, ConnectError>;\n begin(input: BeginAuthorization): Effect.Effect<{ id: string; authorizationUrl: string }, ConnectError>;\n complete(input: {\n callbackUrl: string;\n principalId?: string;\n }): Effect.Effect<OAuthConnectionRecord, ConnectError>;\n clientCredentials(input: {\n applicationId: string;\n connectionId?: string;\n properties?: Record<string, unknown>;\n }): Effect.Effect<OAuthConnectionRecord, ConnectError>;\n refresh(connectionId: string): Effect.Effect<OAuthConnectionRecord, ConnectError>;\n disconnect(connectionId: string): Effect.Effect<void, ConnectError>;\n forget(connectionId: string): Effect.Effect<void, ConnectError>;\n /** Expire every credential-operation lease, so the next refresh or reconnect treats it\n * as interrupted. Only a store's sole owner may call this, at startup: any lease it finds\n * was left by a process that stopped mid-operation, not one still running.\n */\n releaseOperations(): Effect.Effect<number, ConnectError>;\n /** Indexed, bounded maintenance. Does not delete connection identities. */\n collectExpired(options?: {\n limit?: number;\n }): Effect.Effect<{ attempts: number; refreshTokens: number }, ConnectError>;\n}\nexport interface ConnectCredentialValues {\n encrypt<A, AI>(schema: Schema.Codec<A, AI>, value: A): Effect.Effect<Encrypted<A>, unknown>;\n decrypt<A, AI>(schema: Schema.Codec<A, AI>, value: Encrypted<A>): Effect.Effect<A, unknown>;\n evict(value: Encrypted<unknown>): Effect.Effect<void, unknown>;\n}\nexport interface OAuthAuthorityOptions {\n store: ConnectStore;\n values: ConnectCredentialValues;\n oauth(input: {\n application: OAuthApplicationRecord;\n serviceInstance: ServiceInstanceRecord;\n }): Effect.Effect<ConnectOAuthService, ConnectError>;\n /** Populate application ownership properties in the same commit as token storage. */\n connectionProperties?(\n attempt: OAuthAuthorizationAttemptRecord\n ): Effect.Effect<Record<string, unknown>, ConnectError>;\n}\nexport class OAuthAuthority extends Context.Service<OAuthAuthority, OAuthAuthorityService>()(\n \"@party-stack/connect/OAuthAuthority\"\n) {\n static readonly layer = (options: OAuthAuthorityOptions) =>\n Layer.effect(OAuthAuthority, makeOAuthAuthority(options));\n}\nconst instant = (milliseconds: number) => Temporal.Instant.fromEpochMilliseconds(milliseconds);\nconst expired = (time: Temporal.Instant | undefined, now: number) =>\n time !== undefined && time.epochMilliseconds <= now;\nconst guardUrl = (value: string) =>\n Effect.try({\n try: () => {\n const url = new URL(value);\n if (\n url.protocol !== \"https:\" &&\n !(url.protocol === \"http:\" && [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname))\n )\n throw new Error();\n return url;\n },\n catch: () => connectError(\"Configuration\", \"OAuth URLs require HTTPS (or HTTP on localhost).\"),\n });\n\n// Schemes that can execute, embed or read local content are never redirect targets.\nconst unsafeRedirectSchemes = new Set([\n \"about:\",\n \"blob:\",\n \"data:\",\n \"file:\",\n \"filesystem:\",\n \"ftp:\",\n \"javascript:\",\n \"vbscript:\",\n \"ws:\",\n \"wss:\",\n]);\nconst nativeRedirect = (url: URL) =>\n /^[a-z][a-z0-9+.-]*:$/.test(url.protocol) &&\n url.protocol !== \"http:\" &&\n url.protocol !== \"https:\" &&\n !unsafeRedirectSchemes.has(url.protocol) &&\n !url.username &&\n !url.password &&\n !url.port &&\n !url.hash;\n/** Network redirects keep the HTTPS policy. A native application may instead\n * receive its callback at a custom scheme, but only at the exact redirect its\n * trusted OAuth application registration declares; callers cannot introduce one.\n */\nconst guardRedirectUrl = (value: string, registered: string | undefined) =>\n Effect.try({\n try: () => {\n const url = new URL(value);\n if (\n url.protocol === \"https:\" ||\n (url.protocol === \"http:\" && [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname))\n )\n return url;\n if (registered !== undefined && value === registered && nativeRedirect(url)) return url;\n throw new Error();\n },\n catch: () =>\n connectError(\n \"Configuration\",\n \"OAuth redirect URLs require HTTPS, HTTP on localhost, or the application's registered native redirect.\"\n ),\n });\n/** Callback URLs are parsed before the attempt is known; its accepted redirect\n * then decides the exact scheme, host and path. URL.origin is \"null\" for custom\n * schemes, so compare those parts explicitly.\n */\nconst sameRedirectTarget = (expected: URL, callback: URL) =>\n expected.protocol === callback.protocol &&\n expected.host === callback.host &&\n expected.pathname === callback.pathname &&\n expected.username === callback.username &&\n expected.password === callback.password;\n\n/** One credential authority, usable by both device and HTTP entry points. */\nexport const makeOAuthAuthority = (options: OAuthAuthorityOptions): Effect.Effect<OAuthAuthorityService> =>\n Effect.sync(() => {\n const { store, values } = options;\n const read = Effect.fnUntraced(function* (id: string) {\n const record = yield* store.get(\"OAuthConnection\", id);\n if (!record) return yield* connectError(\"NotFound\", \"Connection is unavailable.\");\n return record;\n });\n const configured = Effect.fnUntraced(function* (id: string) {\n const application = yield* store.get(\"OAuthApplication\", id);\n if (!application) return yield* connectError(\"NotFound\", \"OAuth application is unavailable.\");\n const serviceInstance = yield* store.get(\"ServiceInstance\", application.serviceInstance);\n if (!serviceInstance) return yield* connectError(\"NotFound\", \"Service instance is unavailable.\");\n return { application, oauth: yield* options.oauth({ application, serviceInstance }) };\n });\n const decrypt = (value: Encrypted<string>) =>\n values.decrypt(Schema.String, value).pipe(\n Effect.map(Redacted.make),\n Effect.mapError(() => connectError(\"Storage\", \"Credential decryption failed.\"))\n );\n const encrypt = (value: string) =>\n values\n .encrypt(Schema.String, value)\n .pipe(Effect.mapError(() => connectError(\"Storage\", \"Credential encryption failed.\")));\n const evict = (value: Encrypted<string> | undefined) =>\n value\n ? values\n .evict(value)\n .pipe(\n Effect.mapError(() => connectError(\"Storage\", \"Credential deletion failed.\", true))\n )\n : Effect.void;\n const saveTokens = Effect.fnUntraced(function* (record: OAuthConnectionRecord, tokens: OAuthTokens) {\n if (record.userId && record.userId !== tokens.userId)\n return yield* connectError(\n \"NeedsAuthentication\",\n \"Provider identity changed; reconnect explicitly.\"\n );\n const next: OAuthConnectionRecord = {\n ...record,\n status: \"active\",\n userId: tokens.userId,\n accessToken: yield* encrypt(tokens.accessToken),\n accessTokenExpiresAt: tokens.accessTokenExpiresAt,\n refreshToken: tokens.refreshToken ? yield* encrypt(tokens.refreshToken) : undefined,\n refreshTokenExpiresAt: tokens.refreshToken ? tokens.refreshTokenExpiresAt : undefined,\n grantedScopes: tokens.grantedScopes,\n operationId: undefined,\n operationExpiresAt: undefined,\n };\n yield* store.put(\"OAuthConnection\", next);\n yield* evict(record.accessToken);\n yield* evict(record.refreshToken);\n return next;\n });\n const busy = Effect.fnUntraced(function* (record: OAuthConnectionRecord, recovery = false) {\n if (!record.operationId) return;\n const now = yield* Clock.currentTimeMillis;\n if (!expired(record.operationExpiresAt, now))\n return yield* connectError(\"Busy\", \"Connection operation is in progress.\", true);\n if (recovery) return;\n // A refresh may have rotated the token before its reply was lost. Never retry blindly.\n return yield* connectError(\n \"NeedsAuthentication\",\n \"An interrupted credential operation requires reconnection.\"\n );\n });\n const finish = Effect.fnUntraced(function* (record: OAuthConnectionRecord, id: string) {\n const current = yield* read(record.id);\n if (current.operationId !== id)\n return yield* connectError(\"Busy\", \"Connection changed during the credential operation.\");\n return current;\n });\n const refresh = Effect.fn(\"Connect.refresh\")(function* (connectionId: string) {\n const operationId = crypto.randomUUID();\n const record = yield* store.transaction(\n Effect.gen(function* () {\n const current = yield* read(connectionId);\n if (current.operationId) {\n if (!expired(current.operationExpiresAt, yield* Clock.currentTimeMillis))\n return yield* connectError(\"Busy\", \"Connection operation is in progress.\", true);\n // An interrupted refresh may have rotated the refresh token before its\n // reply was lost, so never retry it blindly; save that the connection\n // needs a sign-in. Client credentials hold no such token: claim and fetch anew.\n const application = yield* store.get(\"OAuthApplication\", current.application);\n if (application?.flow !== \"client-credentials\") {\n yield* evict(current.refreshToken);\n yield* store.put(\"OAuthConnection\", {\n ...current,\n status: \"needs-auth\",\n refreshToken: undefined,\n refreshTokenExpiresAt: undefined,\n operationId: undefined,\n operationExpiresAt: undefined,\n });\n return undefined;\n }\n }\n if (current.status !== \"active\")\n return yield* connectError(\"NeedsAuthentication\", \"Reconnect this connection.\");\n const next = {\n ...current,\n operationId,\n operationExpiresAt: instant((yield* Clock.currentTimeMillis) + 60_000),\n };\n yield* store.put(\"OAuthConnection\", next);\n return next;\n })\n );\n if (!record)\n return yield* connectError(\n \"NeedsAuthentication\",\n \"An interrupted credential operation requires reconnection.\"\n );\n const request = Effect.gen(function* () {\n const { application, oauth } = yield* configured(record.application);\n let tokens: OAuthTokens;\n if (application.flow === \"client-credentials\") tokens = yield* oauth.clientCredentials;\n else {\n if (\n !record.refreshToken ||\n expired(record.refreshTokenExpiresAt, yield* Clock.currentTimeMillis)\n )\n return yield* connectError(\n \"NeedsAuthentication\",\n \"Refresh credentials are unavailable or expired.\"\n );\n tokens = yield* oauth.refresh(Redacted.value(yield* decrypt(record.refreshToken)));\n if (!tokens.refreshToken)\n tokens = {\n ...tokens,\n refreshToken: Redacted.value(yield* decrypt(record.refreshToken)),\n refreshTokenExpiresAt: record.refreshTokenExpiresAt,\n };\n }\n return yield* store.transaction(\n Effect.gen(function* () {\n const current = yield* finish(record, operationId);\n return yield* saveTokens(current, tokens);\n })\n );\n }).pipe(\n Effect.timeout(45_000),\n Effect.catchTag(\"TimeoutError\", () =>\n Effect.fail(\n connectError(\n \"NeedsAuthentication\",\n \"Credential exchange timed out; reconnect before retrying.\"\n )\n )\n )\n );\n return yield* request.pipe(\n Effect.catch((error) =>\n store\n .transaction(\n Effect.gen(function* () {\n const current = yield* finish(record, operationId);\n if (error.kind === \"NeedsAuthentication\") {\n yield* evict(current.refreshToken);\n yield* store.put(\"OAuthConnection\", {\n ...current,\n refreshToken: undefined,\n refreshTokenExpiresAt: undefined,\n status: \"needs-auth\",\n operationId: undefined,\n operationExpiresAt: undefined,\n });\n } else if (error.kind !== \"Storage\")\n yield* store.put(\"OAuthConnection\", {\n ...current,\n operationId: undefined,\n operationExpiresAt: undefined,\n });\n })\n )\n .pipe(Effect.andThen(Effect.fail(error)))\n )\n );\n });\n return OAuthAuthority.of({\n connectionForApplication: Effect.fn(\"Connect.connectionForApplication\")(function* (\n applicationId: string\n ) {\n const application = yield* store.get(\"OAuthApplication\", applicationId);\n if (!application) return yield* connectError(\"NotFound\", \"OAuth application is unavailable.\");\n if (!application.connection) return;\n const connection = yield* read(application.connection);\n if (connection.application !== applicationId)\n return yield* connectError(\n \"Configuration\",\n \"OAuth application points to a connection belonging to another application.\"\n );\n return connection;\n }),\n begin: Effect.fn(\"Connect.begin\")(function* (input: BeginAuthorization) {\n if (input.returnUrl) yield* guardUrl(input.returnUrl);\n const { application, oauth } = yield* configured(input.applicationId);\n yield* guardRedirectUrl(input.redirectUrl, application.redirectUrl);\n if (application.redirectUrl && input.redirectUrl !== application.redirectUrl)\n return yield* connectError(\n \"Forbidden\",\n \"Redirect URL does not match the OAuth application.\"\n );\n if (application.flow !== \"authorization-code\")\n return yield* connectError(\n \"Configuration\",\n \"This application does not support interactive authorization.\"\n );\n const id = oauth4webapi.generateRandomState();\n const verifier = oauth4webapi.generateRandomCodeVerifier();\n const challenge = yield* Effect.tryPromise({\n try: () => oauth4webapi.calculatePKCECodeChallenge(verifier),\n catch: () => connectError(\"Configuration\", \"Could not generate PKCE challenge.\"),\n });\n const authorizationUrl = yield* oauth.authorizationUrl({\n state: id,\n codeChallenge: challenge,\n redirectUrl: input.redirectUrl,\n });\n yield* guardUrl(authorizationUrl);\n yield* store.transaction(\n Effect.gen(function* () {\n if (input.connectionId) {\n const previous = yield* read(input.connectionId);\n if (previous.application !== input.applicationId)\n return yield* connectError(\n \"Forbidden\",\n \"Connection belongs to another application.\"\n );\n yield* busy(previous, true);\n }\n yield* store.put(\"OAuthAuthorizationAttempt\", {\n ...input.properties,\n id,\n application: input.applicationId,\n principalId: input.principalId,\n connectionId: input.connectionId ?? crypto.randomUUID(),\n redirectUrl: input.redirectUrl,\n returnUrl: input.returnUrl,\n codeVerifier: yield* encrypt(verifier),\n expiresAt: instant((yield* Clock.currentTimeMillis) + 600_000),\n status: \"pending\",\n });\n })\n );\n return { id, authorizationUrl };\n }),\n complete: Effect.fn(\"Connect.complete\")(function* (input: {\n callbackUrl: string;\n principalId?: string;\n }) {\n const callback = yield* Effect.try({\n try: () => new URL(input.callbackUrl),\n catch: () => connectError(\"InvalidAttempt\", \"Authorization callback URL is invalid.\"),\n });\n const id = callback.searchParams.get(\"state\");\n if (!id)\n return yield* connectError(\"InvalidAttempt\", \"Authorization attempt is unavailable.\");\n const attempt = yield* store.transaction(\n Effect.gen(function* () {\n const current = yield* store.get(\"OAuthAuthorizationAttempt\", id);\n if (\n !current ||\n current.principalId !== input.principalId ||\n expired(current.expiresAt, yield* Clock.currentTimeMillis)\n )\n return yield* connectError(\n \"InvalidAttempt\",\n \"Authorization attempt is unavailable.\"\n );\n const expected = new URL(current.redirectUrl);\n if (!sameRedirectTarget(expected, callback))\n return yield* connectError(\n \"InvalidAttempt\",\n \"Authorization callback URL does not match.\"\n );\n if (current.status === \"completed\") return current;\n if (current.status !== \"pending\")\n return yield* connectError(\n \"InvalidAttempt\",\n \"Authorization attempt was already consumed; start again.\"\n );\n yield* store.put(\"OAuthAuthorizationAttempt\", { ...current, status: \"exchanging\" });\n return current;\n })\n );\n if (attempt.status === \"completed\") {\n if (!attempt.connectionId)\n return yield* connectError(\n \"InvalidAttempt\",\n \"Completed authorization has no connection.\"\n );\n return yield* read(attempt.connectionId);\n }\n const exchange = Effect.gen(function* () {\n const { application, oauth } = yield* configured(attempt.application);\n const tokens = yield* oauth.exchange({\n callbackUrl: input.callbackUrl,\n state: id,\n redirectUrl: attempt.redirectUrl,\n codeVerifier: Redacted.value(yield* decrypt(attempt.codeVerifier)),\n });\n const extra = options.connectionProperties\n ? yield* options.connectionProperties(attempt)\n : {};\n return yield* store.transaction(\n Effect.gen(function* () {\n const claimed = yield* store.get(\"OAuthAuthorizationAttempt\", id);\n if (!claimed || claimed.status !== \"exchanging\")\n return yield* connectError(\n \"InvalidAttempt\",\n \"Authorization attempt is no longer available.\"\n );\n const requested = yield* store.get(\"OAuthConnection\", attempt.connectionId);\n const matches = requested\n ? []\n : yield* store.load(\"OAuthConnection\", {\n where: and(\n eq(field(\"application\"), attempt.application),\n eq(field(\"userId\"), tokens.userId)\n ),\n });\n // Trusted application ownership fields participate in reuse;\n // two projects/principals can still keep separate bindings.\n const reusable = matches.find((row) =>\n Object.entries(extra).every(\n ([name, value]) =>\n JSON.stringify((row as Record<string, unknown>)[name]) ===\n JSON.stringify(value)\n )\n );\n const connectionId = requested?.id ?? reusable?.id ?? attempt.connectionId;\n const current = yield* store.get(\"OAuthConnection\", connectionId);\n if (current) {\n if (current.application !== attempt.application)\n return yield* connectError(\n \"Forbidden\",\n \"Connection belongs to another application.\"\n );\n }\n // A completed login supersedes an in-flight refresh. Clearing\n // operationId fences its late result in finish().\n const next = yield* saveTokens(\n {\n ...extra,\n ...current,\n id: connectionId,\n application: attempt.application,\n title: current?.title ?? application.title,\n status: \"active\",\n },\n tokens\n );\n const latestConnector = yield* store.get(\"OAuthApplication\", application.id);\n if (!latestConnector)\n return yield* connectError(\"NotFound\", \"OAuth application is unavailable.\");\n yield* store.put(\"OAuthApplication\", { ...latestConnector, connection: next.id });\n yield* store.put(\"OAuthAuthorizationAttempt\", {\n ...attempt,\n connectionId: next.id,\n status: \"completed\",\n });\n yield* evict(attempt.codeVerifier);\n return next;\n })\n );\n }).pipe(\n Effect.timeout(45_000),\n Effect.catchTag(\"TimeoutError\", () =>\n Effect.fail(\n connectError(\"Provider\", \"Authorization exchange timed out; start again.\")\n )\n )\n );\n return yield* exchange.pipe(\n Effect.catch((error) =>\n Effect.andThen(\n store.transaction(\n Effect.gen(function* () {\n const claimed = yield* store.get(\"OAuthAuthorizationAttempt\", id);\n if (!claimed || claimed.status !== \"exchanging\") return;\n yield* store.put(\"OAuthAuthorizationAttempt\", {\n ...attempt,\n status: \"failed\",\n });\n yield* evict(attempt.codeVerifier);\n })\n ),\n Effect.fail(error)\n )\n )\n );\n }),\n clientCredentials: Effect.fn(\"Connect.clientCredentials\")(function* (input: {\n applicationId: string;\n connectionId?: string;\n properties?: Record<string, unknown>;\n }) {\n const { application } = yield* configured(input.applicationId);\n if (application.flow !== \"client-credentials\")\n return yield* connectError(\n \"Configuration\",\n \"This application does not use client credentials.\"\n );\n const connectionId = input.connectionId ?? application.connection ?? crypto.randomUUID();\n yield* store.transaction(\n Effect.gen(function* () {\n const existing = yield* store.get(\"OAuthConnection\", connectionId);\n if (existing && existing.application !== application.id)\n return yield* connectError(\n \"Forbidden\",\n \"Connection belongs to another application.\"\n );\n // Reconnecting is how a client-credentials connection recovers from an\n // interrupted operation, so an expired lease does not block it.\n if (existing) yield* busy(existing, true);\n yield* store.put(\"OAuthConnection\", {\n ...input.properties,\n ...existing,\n id: connectionId,\n title: existing?.title ?? application.title,\n application: application.id,\n status: \"active\",\n operationId: undefined,\n operationExpiresAt: undefined,\n });\n const latest = yield* store.get(\"OAuthApplication\", application.id);\n if (!latest)\n return yield* connectError(\"NotFound\", \"OAuth application is unavailable.\");\n yield* store.put(\"OAuthApplication\", { ...latest, connection: connectionId });\n })\n );\n return yield* refresh(connectionId);\n }),\n refresh,\n disconnect: Effect.fn(\"Connect.disconnect\")(function* (id: string) {\n // Detach credentials atomically first. Revocation failure must not restore local access.\n const record = yield* store.transaction(\n Effect.gen(function* () {\n const current = yield* read(id);\n const token = current.refreshToken ?? current.accessToken;\n const plaintext = token\n ? yield* decrypt(token).pipe(Effect.catch(() => Effect.succeed(undefined)))\n : undefined;\n yield* store.put(\"OAuthConnection\", {\n ...current,\n status: \"inactive\",\n operationId: undefined,\n operationExpiresAt: undefined,\n accessToken: undefined,\n accessTokenExpiresAt: undefined,\n refreshToken: undefined,\n refreshTokenExpiresAt: undefined,\n });\n yield* evict(current.accessToken);\n yield* evict(current.refreshToken);\n return { current, plaintext };\n })\n );\n if (record.plaintext) {\n const { oauth } = yield* configured(record.current.application);\n if (oauth.revoke) yield* oauth.revoke(Redacted.value(record.plaintext));\n }\n }),\n forget: Effect.fn(\"Connect.forget\")(function* (id: string) {\n const removed = yield* store.transaction(\n Effect.gen(function* () {\n const current = yield* store.get(\"OAuthConnection\", id);\n const token = current?.refreshToken ?? current?.accessToken;\n const plaintext = token\n ? yield* decrypt(token).pipe(Effect.catch(() => Effect.succeed(undefined)))\n : undefined;\n const attempts = yield* store.load(\"OAuthAuthorizationAttempt\", {\n where: eq(field(\"connectionId\"), id),\n });\n for (const attempt of attempts) {\n yield* evict(attempt.codeVerifier);\n yield* store.delete(\"OAuthAuthorizationAttempt\", attempt.id);\n }\n const applications = yield* store.load(\"OAuthApplication\", {\n where: eq(field(\"connection\"), id),\n });\n for (const application of applications)\n yield* store.put(\"OAuthApplication\", { ...application, connection: undefined });\n if (current) {\n yield* evict(current.accessToken);\n yield* evict(current.refreshToken);\n yield* store.delete(\"OAuthConnection\", id);\n }\n return { current, plaintext };\n })\n );\n // Local deletion commits before remote revocation, including when\n // revocation fails. Action reference validation remains at the boundary.\n if (removed.current && removed.plaintext) {\n const { oauth } = yield* configured(removed.current.application);\n if (oauth.revoke) yield* oauth.revoke(Redacted.value(removed.plaintext));\n }\n }),\n releaseOperations: Effect.fn(\"Connect.releaseOperations\")(function* () {\n return yield* store.transaction(\n Effect.gen(function* () {\n const held = yield* store.load(\"OAuthConnection\", {\n where: ne(field(\"operationId\"), undefined),\n });\n for (const record of held)\n yield* store.put(\"OAuthConnection\", {\n ...record,\n operationExpiresAt: instant(0),\n });\n return held.length;\n })\n );\n }),\n collectExpired: Effect.fn(\"Connect.collectExpired\")(function* ({\n limit = 100,\n }: { limit?: number } = {}) {\n if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1000)\n return yield* connectError(\"Configuration\", \"GC batch size must be between 1 and 1000.\");\n return yield* store.transaction(\n Effect.gen(function* () {\n const now = instant(yield* Clock.currentTimeMillis);\n const attempts = yield* store.load(\"OAuthAuthorizationAttempt\", {\n where: lte(field(\"expiresAt\"), now),\n orderBy: [{ field: field(\"expiresAt\") }],\n limit,\n });\n for (const attempt of attempts) {\n yield* evict(attempt.codeVerifier);\n yield* store.delete(\"OAuthAuthorizationAttempt\", attempt.id);\n }\n const connections = yield* store.load(\"OAuthConnection\", {\n where: and(\n ne(field(\"refreshTokenExpiresAt\"), undefined),\n lte(field(\"refreshTokenExpiresAt\"), now),\n eq(field(\"operationId\"), undefined)\n ),\n orderBy: [{ field: field(\"refreshTokenExpiresAt\") }],\n limit,\n });\n for (const record of connections) {\n yield* evict(record.refreshToken);\n yield* store.put(\"OAuthConnection\", {\n ...record,\n refreshToken: undefined,\n refreshTokenExpiresAt: undefined,\n status: \"needs-auth\",\n });\n }\n // External sessions can be extended upstream. Revalidate\n // them on demand instead of declaring a cached expiry final.\n const expiredConnections = yield* store.load(\"ApiKeyConnection\", {\n where: and(\n eq(field(\"status\"), \"active\"),\n ne(field(\"expiresAt\"), undefined),\n lte(field(\"expiresAt\"), now)\n ),\n orderBy: [{ field: field(\"expiresAt\") }],\n limit,\n });\n for (const record of expiredConnections)\n yield* store.put(\"ApiKeyConnection\", { ...record, status: \"needs-auth\" });\n return { attempts: attempts.length, refreshTokens: connections.length };\n })\n );\n }),\n });\n });\n"],"mappings":";;;;;;AA2FA,IAAa,iBAAb,MAAa,uBAAuB,QAAQ,QAA+C,CAAC,CACxF,qCACJ,CAAC,CAAC;CACE,OAAgB,SAAS,YACrB,MAAM,OAAO,gBAAgB,mBAAmB,OAAO,CAAC;AAChE;AACA,MAAM,WAAW,iBAAyB,SAAS,QAAQ,sBAAsB,YAAY;AAC7F,MAAM,WAAW,MAAoC,QACjD,SAAS,KAAA,KAAa,KAAK,qBAAqB;AACpD,MAAM,YAAY,UACd,OAAO,IAAI;CACP,WAAW;EACP,MAAM,MAAM,IAAI,IAAI,KAAK;EACzB,IACI,IAAI,aAAa,YACjB,EAAE,IAAI,aAAa,WAAW;GAAC;GAAa;GAAa;EAAO,CAAC,CAAC,SAAS,IAAI,QAAQ,IAEvF,MAAM,IAAI,MAAM;EACpB,OAAO;CACX;CACA,aAAa,aAAa,iBAAiB,kDAAkD;AACjG,CAAC;A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H,GAAG,MAAM,QAAQ,GAAG,QAAQ,GAC5B,GAAG,MAAM,WAAW,GAAG,KAAA,CAAS,GAChC,IAAI,MAAM,WAAW,GAAG,GAAG,CAC/B;KACA,SAAS,CAAC,EAAE,OAAO,MAAM,WAAW,EAAE,CAAC;KACvC;IACJ,CAAC;IACD,KAAK,MAAM,UAAU,oBACjB,OAAO,MAAM,IAAI,oBAAoB;KAAE,GAAG;KAAQ,QAAQ;IAAa,CAAC;IAC5E,OAAO;KAAE,UAAU,SAAS;KAAQ,eAAe,YAAY;IAAO;GAC1E,CAAC,CACL;EACJ,CAAC;CACL,CAAC;AACL,CAAC"}
|
|
1
|
+
{"version":3,"file":"oauthAuthority.js","names":[],"sources":["../../src/core/oauthAuthority.ts"],"sourcesContent":["import { and, eq, field, lte, ne } from \"@party-stack/ontology-storage\";\nimport { Clock, Context, Effect, Layer, Schema, Redacted } from \"effect\";\nimport * as oauth4webapi from \"oauth4webapi\";\nimport { Temporal } from \"temporal-polyfill\";\nimport { connectError, type ConnectError } from \"./errors.js\";\nimport type {\n ServiceInstanceRecord,\n OAuthAuthorizationAttemptRecord,\n OAuthConnectionRecord,\n OAuthApplicationRecord,\n} from \"../spec/index.js\";\nimport type { ConnectStore } from \"./store.js\";\nimport type { Encrypted } from \"@party-stack/ontology-spec/values\";\n\nexport interface OAuthTokens {\n accessToken: string;\n accessTokenExpiresAt?: Temporal.Instant;\n refreshToken?: string;\n refreshTokenExpiresAt?: Temporal.Instant;\n grantedScopes?: string;\n userId: string;\n}\nexport interface ConnectOAuthService {\n authorizationUrl(input: {\n state: string;\n codeChallenge: string;\n redirectUrl: string;\n }): Effect.Effect<string, ConnectError>;\n exchange(input: {\n callbackUrl: string;\n state: string;\n codeVerifier: string;\n redirectUrl: string;\n }): Effect.Effect<OAuthTokens, ConnectError>;\n refresh(refreshToken: string): Effect.Effect<OAuthTokens, ConnectError>;\n clientCredentials: Effect.Effect<OAuthTokens, ConnectError>;\n revoke?(token: string): Effect.Effect<void, ConnectError>;\n}\nexport interface BeginAuthorization {\n applicationId: string;\n principalId?: string;\n redirectUrl: string;\n returnUrl?: string;\n connectionId?: string;\n /** Trusted application fields; reserved attempt fields always take precedence. */\n properties?: Record<string, unknown>;\n}\nexport interface OAuthAuthorityService {\n connectionForApplication(\n applicationId: string\n ): Effect.Effect<OAuthConnectionRecord | undefined, ConnectError>;\n begin(input: BeginAuthorization): Effect.Effect<{ id: string; authorizationUrl: string }, ConnectError>;\n complete(input: {\n callbackUrl: string;\n principalId?: string;\n }): Effect.Effect<OAuthConnectionRecord, ConnectError>;\n clientCredentials(input: {\n applicationId: string;\n connectionId?: string;\n properties?: Record<string, unknown>;\n }): Effect.Effect<OAuthConnectionRecord, ConnectError>;\n refresh(connectionId: string): Effect.Effect<OAuthConnectionRecord, ConnectError>;\n disconnect(connectionId: string): Effect.Effect<void, ConnectError>;\n forget(connectionId: string): Effect.Effect<void, ConnectError>;\n /** Expire every credential-operation lease, so the next refresh or reconnect treats it\n * as interrupted. Only a store's sole owner may call this, at startup: any lease it finds\n * was left by a process that stopped mid-operation, not one still running.\n */\n releaseOperations(): Effect.Effect<number, ConnectError>;\n /** Indexed, bounded maintenance. Does not delete connection identities. */\n collectExpired(options?: {\n limit?: number;\n }): Effect.Effect<{ attempts: number; refreshTokens: number }, ConnectError>;\n}\nexport interface ConnectCredentialValues {\n encrypt<A, AI>(schema: Schema.Codec<A, AI>, value: A): Effect.Effect<Encrypted<A>, unknown>;\n decrypt<A, AI>(schema: Schema.Codec<A, AI>, value: Encrypted<A>): Effect.Effect<A, unknown>;\n evict(value: Encrypted<unknown>): Effect.Effect<void, unknown>;\n}\nexport interface OAuthAuthorityOptions {\n store: ConnectStore;\n values: ConnectCredentialValues;\n oauth(input: {\n application: OAuthApplicationRecord;\n serviceInstance: ServiceInstanceRecord;\n }): Effect.Effect<ConnectOAuthService, ConnectError>;\n /** Populate application ownership properties in the same commit as token storage. */\n connectionProperties?(\n attempt: OAuthAuthorizationAttemptRecord\n ): Effect.Effect<Record<string, unknown>, ConnectError>;\n}\nexport class OAuthAuthority extends Context.Service<OAuthAuthority, OAuthAuthorityService>()(\n \"@party-stack/connect/OAuthAuthority\"\n) {\n static readonly layer = (options: OAuthAuthorityOptions) =>\n Layer.effect(OAuthAuthority, makeOAuthAuthority(options));\n}\nconst instant = (milliseconds: number) => Temporal.Instant.fromEpochMilliseconds(milliseconds);\nconst expired = (time: Temporal.Instant | undefined, now: number) =>\n time !== undefined && time.epochMilliseconds <= now;\nconst guardUrl = (value: string) =>\n Effect.try({\n try: () => {\n const url = new URL(value);\n if (\n url.protocol !== \"https:\" &&\n !(url.protocol === \"http:\" && [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname))\n )\n throw new Error();\n return url;\n },\n catch: () => connectError(\"Configuration\", \"OAuth URLs require HTTPS (or HTTP on localhost).\"),\n });\n\n// Schemes that can execute, embed or read local content are never redirect targets.\nconst unsafeRedirectSchemes = new Set([\n \"about:\",\n \"blob:\",\n \"data:\",\n \"file:\",\n \"filesystem:\",\n \"ftp:\",\n \"javascript:\",\n \"vbscript:\",\n \"ws:\",\n \"wss:\",\n]);\nconst nativeRedirect = (url: URL) =>\n /^[a-z][a-z0-9+.-]*:$/.test(url.protocol) &&\n url.protocol !== \"http:\" &&\n url.protocol !== \"https:\" &&\n !unsafeRedirectSchemes.has(url.protocol) &&\n !url.username &&\n !url.password &&\n !url.port &&\n !url.hash;\n/** Network redirects keep the HTTPS policy. A native application may instead\n * receive its callback at a custom scheme, but only at the exact redirect its\n * trusted OAuth application registration declares; callers cannot introduce one.\n */\nconst guardRedirectUrl = (value: string, registered: string | undefined) =>\n Effect.try({\n try: () => {\n const url = new URL(value);\n if (\n url.protocol === \"https:\" ||\n (url.protocol === \"http:\" && [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname))\n )\n return url;\n if (registered !== undefined && value === registered && nativeRedirect(url)) return url;\n throw new Error();\n },\n catch: () =>\n connectError(\n \"Configuration\",\n \"OAuth redirect URLs require HTTPS, HTTP on localhost, or the application's registered native redirect.\"\n ),\n });\n/** Callback URLs are parsed before the attempt is known; its accepted redirect\n * then decides the exact scheme, host and path. URL.origin is \"null\" for custom\n * schemes, so compare those parts explicitly.\n */\nconst sameRedirectTarget = (expected: URL, callback: URL) =>\n expected.protocol === callback.protocol &&\n expected.host === callback.host &&\n expected.pathname === callback.pathname &&\n expected.username === callback.username &&\n expected.password === callback.password;\n\n/** One credential authority, usable by both device and HTTP entry points. */\nexport const makeOAuthAuthority = (options: OAuthAuthorityOptions): Effect.Effect<OAuthAuthorityService> =>\n Effect.sync(() => {\n const { store, values } = options;\n const read = Effect.fnUntraced(function* (id: string) {\n const record = yield* store.get(\"OAuthConnection\", id);\n if (!record) return yield* connectError(\"NotFound\", \"Connection is unavailable.\");\n return record;\n });\n const configured = Effect.fnUntraced(function* (id: string) {\n const application = yield* store.get(\"OAuthApplication\", id);\n if (!application) return yield* connectError(\"NotFound\", \"OAuth application is unavailable.\");\n const serviceInstance = yield* store.get(\"ServiceInstance\", application.serviceInstance);\n if (!serviceInstance) return yield* connectError(\"NotFound\", \"Service instance is unavailable.\");\n return { application, oauth: yield* options.oauth({ application, serviceInstance }) };\n });\n const decrypt = (value: Encrypted<string>) =>\n values.decrypt(Schema.String, value).pipe(\n Effect.map(Redacted.make),\n Effect.mapError(() => connectError(\"Storage\", \"Credential decryption failed.\"))\n );\n const encrypt = (value: string) =>\n values\n .encrypt(Schema.String, value)\n .pipe(Effect.mapError(() => connectError(\"Storage\", \"Credential encryption failed.\")));\n const evict = (value: Encrypted<string> | undefined) =>\n value\n ? values\n .evict(value)\n .pipe(\n Effect.mapError(() => connectError(\"Storage\", \"Credential deletion failed.\", true))\n )\n : Effect.void;\n const saveTokens = Effect.fnUntraced(function* (record: OAuthConnectionRecord, tokens: OAuthTokens) {\n if (record.userId && record.userId !== tokens.userId)\n return yield* connectError(\n \"NeedsAuthentication\",\n \"Provider identity changed; reconnect explicitly.\"\n );\n const next: OAuthConnectionRecord = {\n ...record,\n status: \"active\",\n statusReason: undefined,\n userId: tokens.userId,\n accessToken: yield* encrypt(tokens.accessToken),\n accessTokenExpiresAt: tokens.accessTokenExpiresAt,\n refreshToken: tokens.refreshToken ? yield* encrypt(tokens.refreshToken) : undefined,\n refreshTokenExpiresAt: tokens.refreshToken ? tokens.refreshTokenExpiresAt : undefined,\n grantedScopes: tokens.grantedScopes,\n operationId: undefined,\n operationExpiresAt: undefined,\n };\n yield* store.put(\"OAuthConnection\", next);\n yield* evict(record.accessToken);\n yield* evict(record.refreshToken);\n return next;\n });\n const busy = Effect.fnUntraced(function* (record: OAuthConnectionRecord, recovery = false) {\n if (!record.operationId) return;\n const now = yield* Clock.currentTimeMillis;\n if (!expired(record.operationExpiresAt, now))\n return yield* connectError(\"Busy\", \"Connection operation is in progress.\", true);\n if (recovery) return;\n // A refresh may have rotated the token before its reply was lost. Never retry blindly.\n return yield* connectError(\n \"NeedsAuthentication\",\n \"An interrupted credential operation requires reconnection.\"\n );\n });\n const finish = Effect.fnUntraced(function* (record: OAuthConnectionRecord, id: string) {\n const current = yield* read(record.id);\n if (current.operationId !== id)\n return yield* connectError(\"Busy\", \"Connection changed during the credential operation.\");\n return current;\n });\n const refresh = Effect.fn(\"Connect.refresh\")(function* (connectionId: string) {\n const operationId = crypto.randomUUID();\n const record = yield* store.transaction(\n Effect.gen(function* () {\n const current = yield* read(connectionId);\n // An interrupted refresh (the app was killed, or a previous process stopped)\n // may have rotated the refresh token before its reply was lost. Retry with the\n // saved one anyway: that is never worse than giving up. A provider that accepts\n // a rotated token again (Foundry does) renews the session; one that rejects it\n // answers NeedsAuthentication below, which asks for a sign-in as before.\n if (\n current.operationId &&\n !expired(current.operationExpiresAt, yield* Clock.currentTimeMillis)\n )\n return yield* connectError(\"Busy\", \"Connection operation is in progress.\", true);\n if (current.status !== \"active\")\n return yield* connectError(\"NeedsAuthentication\", \"Reconnect this connection.\");\n const next = {\n ...current,\n operationId,\n operationExpiresAt: instant((yield* Clock.currentTimeMillis) + 60_000),\n };\n yield* store.put(\"OAuthConnection\", next);\n return next;\n })\n );\n const request = Effect.gen(function* () {\n const { application, oauth } = yield* configured(record.application);\n let tokens: OAuthTokens;\n if (application.flow === \"client-credentials\") tokens = yield* oauth.clientCredentials;\n else {\n if (\n !record.refreshToken ||\n expired(record.refreshTokenExpiresAt, yield* Clock.currentTimeMillis)\n )\n return yield* connectError(\n \"NeedsAuthentication\",\n \"Refresh credentials are unavailable or expired.\"\n );\n tokens = yield* oauth.refresh(Redacted.value(yield* decrypt(record.refreshToken)));\n if (!tokens.refreshToken)\n tokens = {\n ...tokens,\n refreshToken: Redacted.value(yield* decrypt(record.refreshToken)),\n refreshTokenExpiresAt: record.refreshTokenExpiresAt,\n };\n }\n return yield* store.transaction(\n Effect.gen(function* () {\n const current = yield* finish(record, operationId);\n return yield* saveTokens(current, tokens);\n })\n );\n }).pipe(\n Effect.timeout(45_000),\n // A slow network is not a rejection: keep the saved token and try again later.\n Effect.catchTag(\"TimeoutError\", () =>\n Effect.fail(connectError(\"Provider\", \"Credential exchange timed out.\", true))\n )\n );\n return yield* request.pipe(\n Effect.catch((error) =>\n store\n .transaction(\n Effect.gen(function* () {\n const current = yield* finish(record, operationId);\n if (error.kind === \"NeedsAuthentication\") {\n yield* evict(current.refreshToken);\n yield* store.put(\"OAuthConnection\", {\n ...current,\n refreshToken: undefined,\n refreshTokenExpiresAt: undefined,\n status: \"needs-auth\",\n statusReason: error.message,\n operationId: undefined,\n operationExpiresAt: undefined,\n });\n } else if (error.kind !== \"Storage\")\n yield* store.put(\"OAuthConnection\", {\n ...current,\n operationId: undefined,\n operationExpiresAt: undefined,\n });\n })\n )\n .pipe(\n Effect.andThen(\n error.kind === \"NeedsAuthentication\"\n ? Effect.logWarning(\"Connection needs a sign-in\", {\n connection: record.id,\n reason: error.message,\n })\n : Effect.logWarning(\"Connection refresh failed; keeping the session\", {\n connection: record.id,\n reason: error.message,\n })\n ),\n Effect.andThen(Effect.fail(error))\n )\n )\n );\n });\n return OAuthAuthority.of({\n connectionForApplication: Effect.fn(\"Connect.connectionForApplication\")(function* (\n applicationId: string\n ) {\n const application = yield* store.get(\"OAuthApplication\", applicationId);\n if (!application) return yield* connectError(\"NotFound\", \"OAuth application is unavailable.\");\n if (!application.connection) return;\n const connection = yield* read(application.connection);\n if (connection.application !== applicationId)\n return yield* connectError(\n \"Configuration\",\n \"OAuth application points to a connection belonging to another application.\"\n );\n return connection;\n }),\n begin: Effect.fn(\"Connect.begin\")(function* (input: BeginAuthorization) {\n if (input.returnUrl) yield* guardUrl(input.returnUrl);\n const { application, oauth } = yield* configured(input.applicationId);\n yield* guardRedirectUrl(input.redirectUrl, application.redirectUrl);\n if (application.redirectUrl && input.redirectUrl !== application.redirectUrl)\n return yield* connectError(\n \"Forbidden\",\n \"Redirect URL does not match the OAuth application.\"\n );\n if (application.flow !== \"authorization-code\")\n return yield* connectError(\n \"Configuration\",\n \"This application does not support interactive authorization.\"\n );\n const id = oauth4webapi.generateRandomState();\n const verifier = oauth4webapi.generateRandomCodeVerifier();\n const challenge = yield* Effect.tryPromise({\n try: () => oauth4webapi.calculatePKCECodeChallenge(verifier),\n catch: () => connectError(\"Configuration\", \"Could not generate PKCE challenge.\"),\n });\n const authorizationUrl = yield* oauth.authorizationUrl({\n state: id,\n codeChallenge: challenge,\n redirectUrl: input.redirectUrl,\n });\n yield* guardUrl(authorizationUrl);\n yield* store.transaction(\n Effect.gen(function* () {\n if (input.connectionId) {\n const previous = yield* read(input.connectionId);\n if (previous.application !== input.applicationId)\n return yield* connectError(\n \"Forbidden\",\n \"Connection belongs to another application.\"\n );\n yield* busy(previous, true);\n }\n yield* store.put(\"OAuthAuthorizationAttempt\", {\n ...input.properties,\n id,\n application: input.applicationId,\n principalId: input.principalId,\n connectionId: input.connectionId ?? crypto.randomUUID(),\n redirectUrl: input.redirectUrl,\n returnUrl: input.returnUrl,\n codeVerifier: yield* encrypt(verifier),\n expiresAt: instant((yield* Clock.currentTimeMillis) + 600_000),\n status: \"pending\",\n });\n })\n );\n return { id, authorizationUrl };\n }),\n complete: Effect.fn(\"Connect.complete\")(function* (input: {\n callbackUrl: string;\n principalId?: string;\n }) {\n const callback = yield* Effect.try({\n try: () => new URL(input.callbackUrl),\n catch: () => connectError(\"InvalidAttempt\", \"Authorization callback URL is invalid.\"),\n });\n const id = callback.searchParams.get(\"state\");\n if (!id)\n return yield* connectError(\"InvalidAttempt\", \"Authorization attempt is unavailable.\");\n const attempt = yield* store.transaction(\n Effect.gen(function* () {\n const current = yield* store.get(\"OAuthAuthorizationAttempt\", id);\n if (\n !current ||\n current.principalId !== input.principalId ||\n expired(current.expiresAt, yield* Clock.currentTimeMillis)\n )\n return yield* connectError(\n \"InvalidAttempt\",\n \"Authorization attempt is unavailable.\"\n );\n const expected = new URL(current.redirectUrl);\n if (!sameRedirectTarget(expected, callback))\n return yield* connectError(\n \"InvalidAttempt\",\n \"Authorization callback URL does not match.\"\n );\n if (current.status === \"completed\") return current;\n if (current.status !== \"pending\")\n return yield* connectError(\n \"InvalidAttempt\",\n \"Authorization attempt was already consumed; start again.\"\n );\n yield* store.put(\"OAuthAuthorizationAttempt\", { ...current, status: \"exchanging\" });\n return current;\n })\n );\n if (attempt.status === \"completed\") {\n if (!attempt.connectionId)\n return yield* connectError(\n \"InvalidAttempt\",\n \"Completed authorization has no connection.\"\n );\n return yield* read(attempt.connectionId);\n }\n const exchange = Effect.gen(function* () {\n const { application, oauth } = yield* configured(attempt.application);\n const tokens = yield* oauth.exchange({\n callbackUrl: input.callbackUrl,\n state: id,\n redirectUrl: attempt.redirectUrl,\n codeVerifier: Redacted.value(yield* decrypt(attempt.codeVerifier)),\n });\n const extra = options.connectionProperties\n ? yield* options.connectionProperties(attempt)\n : {};\n return yield* store.transaction(\n Effect.gen(function* () {\n const claimed = yield* store.get(\"OAuthAuthorizationAttempt\", id);\n if (!claimed || claimed.status !== \"exchanging\")\n return yield* connectError(\n \"InvalidAttempt\",\n \"Authorization attempt is no longer available.\"\n );\n const requested = yield* store.get(\"OAuthConnection\", attempt.connectionId);\n const matches = requested\n ? []\n : yield* store.load(\"OAuthConnection\", {\n where: and(\n eq(field(\"application\"), attempt.application),\n eq(field(\"userId\"), tokens.userId)\n ),\n });\n // Trusted application ownership fields participate in reuse;\n // two projects/principals can still keep separate bindings.\n const reusable = matches.find((row) =>\n Object.entries(extra).every(\n ([name, value]) =>\n JSON.stringify((row as Record<string, unknown>)[name]) ===\n JSON.stringify(value)\n )\n );\n const connectionId = requested?.id ?? reusable?.id ?? attempt.connectionId;\n const current = yield* store.get(\"OAuthConnection\", connectionId);\n if (current) {\n if (current.application !== attempt.application)\n return yield* connectError(\n \"Forbidden\",\n \"Connection belongs to another application.\"\n );\n }\n // A completed login supersedes an in-flight refresh. Clearing\n // operationId fences its late result in finish().\n const next = yield* saveTokens(\n {\n ...extra,\n ...current,\n id: connectionId,\n application: attempt.application,\n title: current?.title ?? application.title,\n status: \"active\",\n },\n tokens\n );\n const latestConnector = yield* store.get(\"OAuthApplication\", application.id);\n if (!latestConnector)\n return yield* connectError(\"NotFound\", \"OAuth application is unavailable.\");\n yield* store.put(\"OAuthApplication\", { ...latestConnector, connection: next.id });\n yield* store.put(\"OAuthAuthorizationAttempt\", {\n ...attempt,\n connectionId: next.id,\n status: \"completed\",\n });\n yield* evict(attempt.codeVerifier);\n return next;\n })\n );\n }).pipe(\n Effect.timeout(45_000),\n Effect.catchTag(\"TimeoutError\", () =>\n Effect.fail(\n connectError(\"Provider\", \"Authorization exchange timed out; start again.\")\n )\n )\n );\n return yield* exchange.pipe(\n Effect.catch((error) =>\n Effect.andThen(\n store.transaction(\n Effect.gen(function* () {\n const claimed = yield* store.get(\"OAuthAuthorizationAttempt\", id);\n if (!claimed || claimed.status !== \"exchanging\") return;\n yield* store.put(\"OAuthAuthorizationAttempt\", {\n ...attempt,\n status: \"failed\",\n });\n yield* evict(attempt.codeVerifier);\n })\n ),\n Effect.fail(error)\n )\n )\n );\n }),\n clientCredentials: Effect.fn(\"Connect.clientCredentials\")(function* (input: {\n applicationId: string;\n connectionId?: string;\n properties?: Record<string, unknown>;\n }) {\n const { application } = yield* configured(input.applicationId);\n if (application.flow !== \"client-credentials\")\n return yield* connectError(\n \"Configuration\",\n \"This application does not use client credentials.\"\n );\n const connectionId = input.connectionId ?? application.connection ?? crypto.randomUUID();\n yield* store.transaction(\n Effect.gen(function* () {\n const existing = yield* store.get(\"OAuthConnection\", connectionId);\n if (existing && existing.application !== application.id)\n return yield* connectError(\n \"Forbidden\",\n \"Connection belongs to another application.\"\n );\n // Reconnecting is how a client-credentials connection recovers from an\n // interrupted operation, so an expired lease does not block it.\n if (existing) yield* busy(existing, true);\n yield* store.put(\"OAuthConnection\", {\n ...input.properties,\n ...existing,\n id: connectionId,\n title: existing?.title ?? application.title,\n application: application.id,\n status: \"active\",\n statusReason: undefined,\n operationId: undefined,\n operationExpiresAt: undefined,\n });\n const latest = yield* store.get(\"OAuthApplication\", application.id);\n if (!latest)\n return yield* connectError(\"NotFound\", \"OAuth application is unavailable.\");\n yield* store.put(\"OAuthApplication\", { ...latest, connection: connectionId });\n })\n );\n return yield* refresh(connectionId);\n }),\n refresh,\n disconnect: Effect.fn(\"Connect.disconnect\")(function* (id: string) {\n // Detach credentials atomically first. Revocation failure must not restore local access.\n const record = yield* store.transaction(\n Effect.gen(function* () {\n const current = yield* read(id);\n const token = current.refreshToken ?? current.accessToken;\n const plaintext = token\n ? yield* decrypt(token).pipe(Effect.catch(() => Effect.succeed(undefined)))\n : undefined;\n yield* store.put(\"OAuthConnection\", {\n ...current,\n status: \"inactive\",\n operationId: undefined,\n operationExpiresAt: undefined,\n accessToken: undefined,\n accessTokenExpiresAt: undefined,\n refreshToken: undefined,\n refreshTokenExpiresAt: undefined,\n });\n yield* evict(current.accessToken);\n yield* evict(current.refreshToken);\n return { current, plaintext };\n })\n );\n if (record.plaintext) {\n const { oauth } = yield* configured(record.current.application);\n if (oauth.revoke) yield* oauth.revoke(Redacted.value(record.plaintext));\n }\n }),\n forget: Effect.fn(\"Connect.forget\")(function* (id: string) {\n const removed = yield* store.transaction(\n Effect.gen(function* () {\n const current = yield* store.get(\"OAuthConnection\", id);\n const token = current?.refreshToken ?? current?.accessToken;\n const plaintext = token\n ? yield* decrypt(token).pipe(Effect.catch(() => Effect.succeed(undefined)))\n : undefined;\n const attempts = yield* store.load(\"OAuthAuthorizationAttempt\", {\n where: eq(field(\"connectionId\"), id),\n });\n for (const attempt of attempts) {\n yield* evict(attempt.codeVerifier);\n yield* store.delete(\"OAuthAuthorizationAttempt\", attempt.id);\n }\n const applications = yield* store.load(\"OAuthApplication\", {\n where: eq(field(\"connection\"), id),\n });\n for (const application of applications)\n yield* store.put(\"OAuthApplication\", { ...application, connection: undefined });\n if (current) {\n yield* evict(current.accessToken);\n yield* evict(current.refreshToken);\n yield* store.delete(\"OAuthConnection\", id);\n }\n return { current, plaintext };\n })\n );\n // Local deletion commits before remote revocation, including when\n // revocation fails. Action reference validation remains at the boundary.\n if (removed.current && removed.plaintext) {\n const { oauth } = yield* configured(removed.current.application);\n if (oauth.revoke) yield* oauth.revoke(Redacted.value(removed.plaintext));\n }\n }),\n releaseOperations: Effect.fn(\"Connect.releaseOperations\")(function* () {\n return yield* store.transaction(\n Effect.gen(function* () {\n const held = yield* store.load(\"OAuthConnection\", {\n where: ne(field(\"operationId\"), undefined),\n });\n for (const record of held)\n yield* store.put(\"OAuthConnection\", {\n ...record,\n operationExpiresAt: instant(0),\n });\n return held.length;\n })\n );\n }),\n collectExpired: Effect.fn(\"Connect.collectExpired\")(function* ({\n limit = 100,\n }: { limit?: number } = {}) {\n if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1000)\n return yield* connectError(\"Configuration\", \"GC batch size must be between 1 and 1000.\");\n return yield* store.transaction(\n Effect.gen(function* () {\n const now = instant(yield* Clock.currentTimeMillis);\n const attempts = yield* store.load(\"OAuthAuthorizationAttempt\", {\n where: lte(field(\"expiresAt\"), now),\n orderBy: [{ field: field(\"expiresAt\") }],\n limit,\n });\n for (const attempt of attempts) {\n yield* evict(attempt.codeVerifier);\n yield* store.delete(\"OAuthAuthorizationAttempt\", attempt.id);\n }\n const connections = yield* store.load(\"OAuthConnection\", {\n where: and(\n ne(field(\"refreshTokenExpiresAt\"), undefined),\n lte(field(\"refreshTokenExpiresAt\"), now),\n eq(field(\"operationId\"), undefined)\n ),\n orderBy: [{ field: field(\"refreshTokenExpiresAt\") }],\n limit,\n });\n for (const record of connections) {\n yield* evict(record.refreshToken);\n yield* store.put(\"OAuthConnection\", {\n ...record,\n refreshToken: undefined,\n refreshTokenExpiresAt: undefined,\n status: \"needs-auth\",\n statusReason: \"The saved refresh token expired.\",\n });\n yield* Effect.logWarning(\"Connection needs a sign-in\", {\n connection: record.id,\n reason: \"The saved refresh token expired.\",\n });\n }\n // External sessions can be extended upstream. Revalidate\n // them on demand instead of declaring a cached expiry final.\n const expiredConnections = yield* store.load(\"ApiKeyConnection\", {\n where: and(\n eq(field(\"status\"), \"active\"),\n ne(field(\"expiresAt\"), undefined),\n lte(field(\"expiresAt\"), now)\n ),\n orderBy: [{ field: field(\"expiresAt\") }],\n limit,\n });\n for (const record of expiredConnections) {\n yield* store.put(\"ApiKeyConnection\", {\n ...record,\n status: \"needs-auth\",\n statusReason: \"The API key expired.\",\n });\n yield* Effect.logWarning(\"Connection needs a sign-in\", {\n connection: record.id,\n reason: \"The API key expired.\",\n });\n }\n return { attempts: attempts.length, refreshTokens: connections.length };\n })\n );\n }),\n });\n });\n"],"mappings":";;;;;;AA2FA,IAAa,iBAAb,MAAa,uBAAuB,QAAQ,QAA+C,CAAC,CACxF,qCACJ,CAAC,CAAC;CACE,OAAgB,SAAS,YACrB,MAAM,OAAO,gBAAgB,mBAAmB,OAAO,CAAC;AAChE;AACA,MAAM,WAAW,iBAAyB,SAAS,QAAQ,sBAAsB,YAAY;AAC7F,MAAM,WAAW,MAAoC,QACjD,SAAS,KAAA,KAAa,KAAK,qBAAqB;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QAAQ,OAAO,OAAO,QAAQ,MAAM;EAClF,YAAY,GAAG,GAAG,GAAG,MAAM,OAAO,OAAO,GAAG,GAAG,KAAK,OAAO,OAAO,GAAG,IAAI,cAAc;;;qBAI9E,yBAAsB;EACvB,QAAA;EACG;EACN,KAAA;EACS;aAAmB;;;;;
|
|
1
|
+
{"version":3,"file":"store.d.ts","names":[],"sources":["../../src/core/store.ts"],"mappings":";;;;;;;KAoBK;EACD,iBAAiB;EACjB,kBAAkB;EAClB,iBAAiB;EACjB,2BAA2B;EAC3B,kBAAkB;EAClB,2BAA2B;;;;;iBAKd;EACb,IAAI,gBAAgB,SAAS,MAAM,GAAG,aAAa,OAAO,OAAO,QAAQ,gBAAgB;EACzF,IAAI,gBAAgB,SAAS,MAAM,GAAG,OAAO,QAAQ,KAAK,OAAO,aAAa;EAC9E,OAAO,gBAAgB,SAAS,MAAM,GAAG,aAAa,OAAO,aAAa;EAC1E,KAAK,gBAAgB,SAAS,MAAM,GAAG,OAAO,QAAQ,OAAO,OAAO,QAAQ,MAAM;EAClF,YAAY,GAAG,GAAG,GAAG,MAAM,OAAO,OAAO,GAAG,GAAG,KAAK,OAAO,OAAO,GAAG,IAAI,cAAc;;;qBAI9E,yBAAsB;EACvB,QAAA;EACG;EACN,KAAA;EACS;aAAmB;;;;;2CA8FnC,kWAAA,qCAAA;qBAEW,mBAAgB;EAnGjB,QAAA;EACG;EACN,KAAA;EACS;aAAmB;;MAoGnC,OAAA,OAAA,sDAAA,kWAAA,qCAAA"}
|
package/lib/core/store.js
CHANGED
package/lib/core/store.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.js","names":[],"sources":["../../src/core/store.ts"],"sourcesContent":["import { makeOwnedBackend } from \"@party-stack/ontology-backend/owned\";\nimport { compileEffectSchemas } from \"@party-stack/ontology-spec/effect\";\nimport { field } from \"@party-stack/ontology-storage\";\nimport { Context, Effect } from \"effect\";\nimport { connectOntology } from \"../spec/index.js\";\nimport { connectError, type ConnectError } from \"./errors.js\";\nimport { migrateConnectCredentials } from \"./migrate.js\";\nimport type {\n OAuthConnectionRecord,\n OAuthApplicationRecord,\n ServiceInstanceRecord,\n OAuthAuthorizationAttemptRecord,\n ApiKeyConnectionRecord,\n ExternalSessionConnectionRecord,\n} from \"../spec/index.js\";\nimport type { OwnedReadTransaction, OwnedStorageTransaction } from \"@party-stack/ontology-backend/owned\";\nimport type { OntologyIR } from \"@party-stack/ontology-spec\";\nimport type { Query } from \"@party-stack/ontology-storage\";\nimport type { TablesService } from \"@party-stack/ontology-storage/tables\";\n\ntype Records = {\n ServiceInstance: ServiceInstanceRecord;\n OAuthApplication: OAuthApplicationRecord;\n OAuthConnection: OAuthConnectionRecord;\n OAuthAuthorizationAttempt: OAuthAuthorizationAttemptRecord;\n ApiKeyConnection: ApiKeyConnectionRecord;\n ExternalSessionConnection: ExternalSessionConnectionRecord;\n};\n/** Remote implementations may implement this boundary with trusted ontology actions.\n * transaction must atomically enforce the read/write decisions in its body.\n */\nexport interface ConnectStore {\n get<N extends keyof Records>(name: N, id: string): Effect.Effect<Records[N] | undefined, ConnectError>;\n put<N extends keyof Records>(name: N, value: Records[N]): Effect.Effect<void, ConnectError>;\n delete<N extends keyof Records>(name: N, id: string): Effect.Effect<void, ConnectError>;\n load<N extends keyof Records>(name: N, query: Query): Effect.Effect<Records[N][], ConnectError>;\n transaction<A, E, R>(body: Effect.Effect<A, E, R>): Effect.Effect<A, E | ConnectError, R>;\n}\n\n/** Additional application properties are validated and preserved by the compiled ontology. */\nexport const makeConnectPersistence = Effect.fn(\"Connect.persistence\")(function* (options: {\n tables: TablesService;\n namespace: string;\n ir?: OntologyIR;\n maintenance?: false | { readonly intervalMs?: number };\n}) {\n const ir = options.ir ?? connectOntology;\n const protect = <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n effect.pipe(\n Effect.mapError(() => connectError(\"Storage\", \"Connect storage operation failed.\", true))\n );\n // Compile application extensions, then check that every standard property remains compatible.\n yield* Effect.try({\n try: () => {\n for (const base of connectOntology.objectTypes) {\n const definition = ir.objectTypes.find((candidate) => candidate.name === base.name);\n if (!definition || definition.primaryKey !== base.primaryKey) throw new Error();\n for (const property of base.properties) {\n const actual = definition.properties.find(\n (candidate) => candidate.name === property.name\n );\n if (!actual || JSON.stringify(actual.type) !== JSON.stringify(property.type))\n throw new Error();\n }\n }\n compileEffectSchemas(ir);\n },\n catch: () =>\n connectError(\n \"Configuration\",\n \"Connect definitions must retain their standard properties and primary keys.\"\n ),\n });\n const backend = yield* makeOwnedBackend({\n ...options,\n // Version
|
|
1
|
+
{"version":3,"file":"store.js","names":[],"sources":["../../src/core/store.ts"],"sourcesContent":["import { makeOwnedBackend } from \"@party-stack/ontology-backend/owned\";\nimport { compileEffectSchemas } from \"@party-stack/ontology-spec/effect\";\nimport { field } from \"@party-stack/ontology-storage\";\nimport { Context, Effect } from \"effect\";\nimport { connectOntology } from \"../spec/index.js\";\nimport { connectError, type ConnectError } from \"./errors.js\";\nimport { migrateConnectCredentials } from \"./migrate.js\";\nimport type {\n OAuthConnectionRecord,\n OAuthApplicationRecord,\n ServiceInstanceRecord,\n OAuthAuthorizationAttemptRecord,\n ApiKeyConnectionRecord,\n ExternalSessionConnectionRecord,\n} from \"../spec/index.js\";\nimport type { OwnedReadTransaction, OwnedStorageTransaction } from \"@party-stack/ontology-backend/owned\";\nimport type { OntologyIR } from \"@party-stack/ontology-spec\";\nimport type { Query } from \"@party-stack/ontology-storage\";\nimport type { TablesService } from \"@party-stack/ontology-storage/tables\";\n\ntype Records = {\n ServiceInstance: ServiceInstanceRecord;\n OAuthApplication: OAuthApplicationRecord;\n OAuthConnection: OAuthConnectionRecord;\n OAuthAuthorizationAttempt: OAuthAuthorizationAttemptRecord;\n ApiKeyConnection: ApiKeyConnectionRecord;\n ExternalSessionConnection: ExternalSessionConnectionRecord;\n};\n/** Remote implementations may implement this boundary with trusted ontology actions.\n * transaction must atomically enforce the read/write decisions in its body.\n */\nexport interface ConnectStore {\n get<N extends keyof Records>(name: N, id: string): Effect.Effect<Records[N] | undefined, ConnectError>;\n put<N extends keyof Records>(name: N, value: Records[N]): Effect.Effect<void, ConnectError>;\n delete<N extends keyof Records>(name: N, id: string): Effect.Effect<void, ConnectError>;\n load<N extends keyof Records>(name: N, query: Query): Effect.Effect<Records[N][], ConnectError>;\n transaction<A, E, R>(body: Effect.Effect<A, E, R>): Effect.Effect<A, E | ConnectError, R>;\n}\n\n/** Additional application properties are validated and preserved by the compiled ontology. */\nexport const makeConnectPersistence = Effect.fn(\"Connect.persistence\")(function* (options: {\n tables: TablesService;\n namespace: string;\n ir?: OntologyIR;\n maintenance?: false | { readonly intervalMs?: number };\n}) {\n const ir = options.ir ?? connectOntology;\n const protect = <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n effect.pipe(\n Effect.mapError(() => connectError(\"Storage\", \"Connect storage operation failed.\", true))\n );\n // Compile application extensions, then check that every standard property remains compatible.\n yield* Effect.try({\n try: () => {\n for (const base of connectOntology.objectTypes) {\n const definition = ir.objectTypes.find((candidate) => candidate.name === base.name);\n if (!definition || definition.primaryKey !== base.primaryKey) throw new Error();\n for (const property of base.properties) {\n const actual = definition.properties.find(\n (candidate) => candidate.name === property.name\n );\n if (!actual || JSON.stringify(actual.type) !== JSON.stringify(property.type))\n throw new Error();\n }\n }\n compileEffectSchemas(ir);\n },\n catch: () =>\n connectError(\n \"Configuration\",\n \"Connect definitions must retain their standard properties and primary keys.\"\n ),\n });\n const backend = yield* makeOwnedBackend({\n ...options,\n // Version 4 adds each connection's status reason; version 3 added per-application\n // OAuth scopes. Import earlier records below; credential encryption uses\n // options.namespace, so handles retain their AAD.\n namespace: JSON.stringify([options.namespace, \"connect\", 4]),\n ir,\n mutators: {},\n });\n // Each persistence instance has its own transaction binding. Nested calls compose;\n // concurrent effects and different Connect authorities never share a transaction.\n const CurrentTransaction = Context.Service<OwnedStorageTransaction>(\n `Connect.transaction:${crypto.randomUUID()}`\n );\n const inTransaction = <A, E, R>(body: (tx: OwnedStorageTransaction) => Effect.Effect<A, E, R>) =>\n Effect.serviceOption(CurrentTransaction).pipe(\n Effect.flatMap((current) =>\n current._tag === \"Some\" ? body(current.value) : backend.storage.transaction(body)\n )\n );\n const read = <A, E, R>(body: (tx: OwnedReadTransaction) => Effect.Effect<A, E, R>) =>\n Effect.serviceOption(CurrentTransaction).pipe(\n Effect.flatMap((current) =>\n current._tag === \"Some\" ? body(current.value) : backend.storage.read(body)\n )\n );\n const store: ConnectStore = {\n get: (name, id) =>\n protect(read((tx) => tx.get(name, id))).pipe(\n Effect.map((value) => value as Records[typeof name] | undefined)\n ),\n put: (name, value) => protect(inTransaction((tx) => tx.put(name, value))),\n delete: (name, id) => protect(inTransaction((tx) => tx.delete(name, id))),\n load: (name, query) =>\n protect(read((tx) => tx.loadSubset(name, query))).pipe(\n Effect.map((rows) => rows.map((row) => row.value as Records[typeof name]))\n ),\n transaction: (body) =>\n inTransaction((tx) => body.pipe(Effect.provideService(CurrentTransaction, tx))).pipe(\n Effect.catchTag(\"BackendError\", () =>\n Effect.fail(connectError(\"Storage\", \"Connect transaction failed.\", true))\n )\n ),\n };\n for (const [name, fields] of Object.entries({\n OAuthApplication: [\"serviceInstance\", \"connection\"],\n OAuthConnection: [\n \"application\",\n \"userId\",\n \"accessTokenExpiresAt\",\n \"refreshTokenExpiresAt\",\n \"operationExpiresAt\",\n ],\n OAuthAuthorizationAttempt: [\"expiresAt\", \"application\", \"connectionId\"],\n ApiKeyConnection: [\"serviceInstance\", \"userId\", \"expiresAt\"],\n ExternalSessionConnection: [\"serviceInstance\", \"userId\", \"sessionId\", \"expiresAt\"],\n }))\n for (const property of fields)\n yield* protect(\n backend.storage.transaction((tx) =>\n tx.ensureIndex(name, { name: property, field: field(property) })\n )\n );\n yield* protect(migrateConnectCredentials({ ...options, ir, store }));\n return { store, backend };\n});\n\nexport const makeConnectStore = Effect.fn(\"Connect.store\")(function* (\n options: Parameters<typeof makeConnectPersistence>[0]\n) {\n return (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CAAC,CAAC,WACvD,SACF;CACE,QAAQ,OAAO,uBAAuB,OAAO,EAAA,CAAG;AACpD,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serviceConnections.d.ts","names":[],"sources":["../src/serviceConnections.ts"],"mappings":";;;;;;;;;;iBAsBiB;WACJ,YAAY;WACZ;WACA,iBAAiB;WACjB,QAAQ;;WAER,gBAAgB;;;;;qBAsChB,yBAAsB;WACb,SAAA;WACF,OAAA;WACG,mBAAS;WACR,WAAA;;
|
|
1
|
+
{"version":3,"file":"serviceConnections.d.ts","names":[],"sources":["../src/serviceConnections.ts"],"mappings":";;;;;;;;;;iBAsBiB;WACJ,YAAY;WACZ;WACA,iBAAiB;WACjB,QAAQ;;WAER,gBAAgB;;;;;qBAsChB,yBAAsB;WACb,SAAA;WACF,OAAA;WACG,mBAAS;WACR,WAAA;;EA2fM,UAAA,YAAA,kBAAa,OAAA;;;;;;IAPS,iBAAA;;;;GASlD,6DAAA"}
|
|
@@ -153,7 +153,10 @@ const makeServiceConnections = Effect.fn("Connect.connections")(function* (optio
|
|
|
153
153
|
const renewed = nextCredential !== credential;
|
|
154
154
|
credential = nextCredential;
|
|
155
155
|
if (renewed) credentialGeneration++;
|
|
156
|
-
if (changed || state.status === "error") publish(
|
|
156
|
+
if (changed || state.status === "error") publish(value?.status === "needs-auth" && value.statusReason ? {
|
|
157
|
+
status: "needs-auth",
|
|
158
|
+
error: value.statusReason
|
|
159
|
+
} : { status: value?.status ?? "inactive" }, renewed);
|
|
157
160
|
};
|
|
158
161
|
const watch = backend.changes?.watch ?? backend.watchSubset?.({
|
|
159
162
|
from: {
|
|
@@ -215,15 +218,21 @@ const makeServiceConnections = Effect.fn("Connect.connections")(function* (optio
|
|
|
215
218
|
});
|
|
216
219
|
const scope = yield* Effect.scope;
|
|
217
220
|
const owned = (work) => Effect.suspend(() => scope.state._tag === "Closed" ? Effect.fail(unavailable("The selected connection was released.")) : Effect.acquireUseRelease(Effect.forkIn(work, scope), Fiber.join, Fiber.interrupt));
|
|
218
|
-
const markNeedsAuthentication = (observed) => options.store.transaction(Effect.gen(function* () {
|
|
221
|
+
const markNeedsAuthentication = (observed, reason) => options.store.transaction(Effect.gen(function* () {
|
|
219
222
|
const current = yield* options.store.get(ref.objectType, ref.id);
|
|
220
|
-
if (current?.status
|
|
223
|
+
if (current?.status !== "active" || credentialVersion(current) !== observed) return;
|
|
224
|
+
yield* options.store.put(ref.objectType, {
|
|
221
225
|
...current,
|
|
222
|
-
status: "needs-auth"
|
|
226
|
+
status: "needs-auth",
|
|
227
|
+
statusReason: reason
|
|
228
|
+
});
|
|
229
|
+
yield* Effect.logWarning("Connection needs a sign-in", {
|
|
230
|
+
connection: ref.id,
|
|
231
|
+
reason
|
|
223
232
|
});
|
|
224
233
|
})).pipe(Effect.mapError(connectBackendError), Effect.tapError((cause) => Effect.logError("Could not save connection authentication status", cause)), Effect.ignore, Effect.uninterruptible);
|
|
225
234
|
const failed = Effect.fnUntraced(function* (error, observed) {
|
|
226
|
-
if (isUnauthenticatedError(error)) yield* markNeedsAuthentication(observed);
|
|
235
|
+
if (isUnauthenticatedError(error)) yield* markNeedsAuthentication(observed, "The service rejected the saved credentials. " + error.message);
|
|
227
236
|
return yield* error;
|
|
228
237
|
});
|
|
229
238
|
const verifyExternalSession = Effect.gen(function* () {
|
|
@@ -278,7 +287,7 @@ const makeServiceConnections = Effect.fn("Connect.connections")(function* (optio
|
|
|
278
287
|
return;
|
|
279
288
|
}
|
|
280
289
|
if (ref.objectType !== "OAuthConnection") {
|
|
281
|
-
yield* markNeedsAuthentication(credentialVersion(current));
|
|
290
|
+
yield* markNeedsAuthentication(credentialVersion(current), "The service rejected the saved credentials, and they cannot be renewed.");
|
|
282
291
|
return;
|
|
283
292
|
}
|
|
284
293
|
const result = yield* Effect.result(backend.applyAction({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serviceConnections.js","names":[],"sources":["../src/serviceConnections.ts"],"sourcesContent":["import { BackendError, classifyBackendFailure, isUnauthenticatedError } from \"@party-stack/ontology-backend\";\nimport * as q from \"@party-stack/ontology-spec/query\";\nimport { Clock, Context, Effect, Fiber, Queue, RcMap, Schema, Stream, Schedule, Semaphore } from \"effect\";\nimport { accessTokenNeedsRefresh, connectionAccessToken } from \"./core/accessToken.js\";\nimport { connectBackendError } from \"./core/backend.js\";\nimport { connectError } from \"./core/errors.js\";\nimport { createDefaultConnectionEgressHandlers } from \"./createDefaultConnectionEgressHandlers.js\";\nimport { connectOntology } from \"./spec/index.js\";\nimport type { ConnectStore } from \"./core/store.js\";\nimport type { ConnectionRef, SavedConnection, ServiceConnector } from \"./ServiceConnector.js\";\nimport type { ConnectOntology, ServiceInstanceRecord } from \"./spec/index.js\";\nimport type {\n ConnectionEgress,\n ConnectionEgressHandlers,\n ConnectionLifecycle,\n ConnectionState,\n} from \"./types.js\";\nimport type { OntologyBackendService } from \"@party-stack/ontology-backend\";\n\n/** Scoped identity and egress for one saved connection. Cached data can reopen\n * while authentication is required; actual egress always requires active credentials.\n */\nexport interface ConnectionAccess {\n readonly connection: ConnectionRef;\n readonly userId: string;\n readonly serviceInstance: ServiceInstanceRecord;\n readonly egress: ConnectionEgress;\n /** Pass to the replica that syncs this connection; show apps only its monitor fields. */\n readonly authentication: ConnectionLifecycle;\n}\n\nconst unavailable = (message: string) =>\n new BackendError({\n operation: \"connect.acquire\",\n kind: \"Unauthenticated\",\n retryable: false,\n message,\n });\n\n// Observe the credential actually used by this request, including renewal. A\n// later rejection must not change the status of a newer saved session.\nconst CredentialObserver = Context.Reference<(version: string) => void>(\n \"@party-stack/connect/CredentialObserver\",\n { defaultValue: () => () => {} }\n);\nconst retryAfterRenewal = () =>\n new BackendError({\n operation: \"connect.egress\",\n kind: \"Unavailable\",\n retryable: true,\n actionOutcome: \"not-committed\",\n message: \"The credential was renewed after the service rejected it; retry the request.\",\n });\nconst renewalUnavailable = (cause: BackendError) =>\n new BackendError({\n operation: \"connect.refresh\",\n kind: \"Unavailable\",\n retryable: true,\n actionOutcome: \"not-committed\",\n message: \"The credential could not be renewed yet; retry the request.\",\n cause,\n });\n\n/** Acquire saved identity and egress from ontology records. The map holds only\n * scoped access; the Connect backend remains the sole durable inventory.\n */\nexport const makeServiceConnections = Effect.fn(\"Connect.connections\")(function* (options: {\n readonly backend: OntologyBackendService;\n readonly store: ConnectStore;\n readonly services: readonly ServiceConnector[];\n readonly handlers?: ConnectionEgressHandlers;\n}) {\n const backend = options.backend;\n const services = new Map(options.services.map((service) => [service.service, service]));\n if (services.size !== options.services.length)\n return yield* new BackendError({\n operation: \"connect.configure\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"Service connector names must be unique.\",\n });\n const read = Effect.fnUntraced(function* <N extends keyof ConnectOntology[\"objectTypes\"]>(\n objectType: N,\n id: string\n ) {\n const rows = yield* backend.query({\n select: [\n q.sub(\"rows\", {\n from: { source: { objectType }, binding: \"row\" },\n where: q.eq(q.field(\"row\", \"id\"), q.literal(id)),\n select: connectOntology.objectTypes\n .find((type) => type.name === objectType)!\n .properties.map((property) =>\n q.selectField(property.name, q.field(\"row\", property.name))\n ),\n }),\n ],\n });\n return (rows.rows as ConnectOntology[\"objectTypes\"][N][])[0];\n });\n const reference = Schema.Struct({\n objectType: Schema.Literals([\"OAuthConnection\", \"ApiKeyConnection\", \"ExternalSessionConnection\"]),\n id: Schema.NonEmptyString,\n });\n const codec = Schema.fromJsonString(reference);\n const access = yield* RcMap.make({\n lookup: Effect.fnUntraced(function* (key: string) {\n const ref = yield* Schema.decodeUnknownEffect(codec)(key).pipe(\n Effect.mapError((cause) => classifyBackendFailure(\"connect.acquire\", cause))\n );\n const row = yield* read(ref.objectType, ref.id);\n if (!row || row.status === \"inactive\" || !row.userId)\n return yield* unavailable(\"The selected connection is disconnected.\");\n const instanceId =\n ref.objectType === \"OAuthConnection\"\n ? (yield* read(\n \"OAuthApplication\",\n (row as ConnectOntology[\"objectTypes\"][\"OAuthConnection\"]).application\n ))?.serviceInstance\n : (\n row as\n | ConnectOntology[\"objectTypes\"][\"ApiKeyConnection\"]\n | ConnectOntology[\"objectTypes\"][\"ExternalSessionConnection\"]\n ).serviceInstance;\n const serviceInstance = instanceId ? yield* read(\"ServiceInstance\", instanceId) : undefined;\n if (!serviceInstance)\n return yield* new BackendError({\n operation: \"connect.acquire\",\n kind: \"NotFound\",\n retryable: false,\n message: \"Service instance is unavailable.\",\n });\n const service = services.get(serviceInstance.service);\n if (!service)\n return yield* new BackendError({\n operation: \"connect.acquire\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"Service connector is unavailable.\",\n });\n const currentCredential = Effect.fnUntraced(function* (\n renewEarly = true\n ): Effect.fn.Return<string, BackendError> {\n const current = yield* read(ref.objectType, ref.id);\n if (!current || current.status === \"inactive\")\n return yield* unavailable(\"The selected connection is disconnected.\");\n if (current.status !== \"active\")\n return yield* unavailable(\"The selected connection requires authentication.\");\n if (ref.objectType === \"OAuthConnection\") {\n if (\n renewEarly &&\n accessTokenNeedsRefresh(\n current as ConnectOntology[\"objectTypes\"][\"OAuthConnection\"],\n yield* Clock.currentTimeMillis\n )\n ) {\n // Renew a token that is about to expire through the connection's one\n // renewal, like a rejected one. Requests queued behind it skip their own\n // refresh once the credential changes, even when the new token is also\n // short-lived, and share a failed attempt instead of each retrying it.\n yield* renew(credentialGeneration);\n return yield* currentCredential(false);\n }\n // This manager owns renewal; the helper only reads and decrypts.\n return yield* connectionAccessToken(backend, ref.id, { refresh: false });\n }\n const expiresAt = (\n current as\n | ConnectOntology[\"objectTypes\"][\"ExternalSessionConnection\"]\n | ConnectOntology[\"objectTypes\"][\"ApiKeyConnection\"]\n ).expiresAt;\n if (ref.objectType === \"ExternalSessionConnection\") {\n (yield* CredentialObserver)(credentialVersion(current));\n if (expiresAt && expiresAt.epochMilliseconds <= (yield* Clock.currentTimeMillis)) {\n // Verify through the connection's one renewal: requests that queued for\n // the same expired session share its answer instead of each asking again.\n yield* renew(credentialGeneration, \"expiring\");\n return yield* currentCredential();\n }\n return (current as ConnectOntology[\"objectTypes\"][\"ExternalSessionConnection\"]).sessionId;\n }\n if (expiresAt && expiresAt.epochMilliseconds <= (yield* Clock.currentTimeMillis))\n return yield* unavailable(\"The selected connection has expired.\");\n const apiKey = (current as ConnectOntology[\"objectTypes\"][\"ApiKeyConnection\"]).apiKey;\n if (!apiKey || !backend.encrypted) return yield* unavailable(\"API key is unavailable.\");\n const result = yield* backend.encrypted.decrypt({\n ...apiKey,\n source: { objectType: ref.objectType, primaryKey: ref.id, property: \"apiKey\" },\n });\n return yield* Schema.decodeUnknownEffect(Schema.String)(result.value).pipe(\n Effect.mapError((cause) => classifyBackendFailure(\"connect.credential\", cause))\n );\n });\n let state: ConnectionState = { status: row.status };\n let fingerprint = JSON.stringify(row);\n const credentialVersion = (value: typeof row | undefined) =>\n JSON.stringify(\n !value\n ? null\n : [\n value.status,\n value.userId,\n \"application\" in value\n ? [\n value.application,\n value.accessToken?.ciphertext,\n value.refreshToken?.ciphertext,\n value.operationId,\n ]\n : \"sessionId\" in value\n ? [value.serviceInstance, value.sessionId, value.expiresAt]\n : [value.serviceInstance, value.apiKey?.ciphertext, value.expiresAt],\n ]\n );\n const listeners = new Set<(state: ConnectionState) => void>();\n const publish = (value: ConnectionState, changedCredential = false) => {\n if (!changedCredential && JSON.stringify(state) === JSON.stringify(value)) return;\n state = value;\n for (const listener of listeners) listener(value);\n };\n // The credential itself, not bookkeeping such as an in-progress refresh marker:\n // only a new credential (or a status change) is a new activation.\n const credentialIdentity = (value: typeof row | undefined) =>\n JSON.stringify(\n !value\n ? null\n : [\n value.status,\n value.userId,\n \"application\" in value\n ? value.accessToken?.ciphertext\n : \"sessionId\" in value\n ? [value.sessionId, value.expiresAt]\n : [value.apiKey?.ciphertext, value.expiresAt],\n ]\n );\n let credentialGeneration = 0;\n let credential = credentialIdentity(row);\n const install = (value: typeof row | undefined) => {\n const next = JSON.stringify(value);\n const changed = fingerprint !== next;\n fingerprint = next;\n const nextCredential = credentialIdentity(value);\n const renewed = nextCredential !== credential;\n credential = nextCredential;\n if (renewed) credentialGeneration++;\n if (changed || state.status === \"error\")\n publish({ status: value?.status ?? \"inactive\" }, renewed);\n };\n const watch =\n backend.changes?.watch ??\n backend.watchSubset?.({\n from: { source: { objectType: ref.objectType }, binding: \"connection\" },\n where: q.eq(q.field(\"connection\", \"id\"), q.literal(ref.id)),\n });\n if (watch)\n yield* Stream.runForEach(\n Stream.unwrap(\n watch.pipe(\n // Acquisition has registered and buffered the feed. Re-read\n // after every acquisition, including a retry, before consuming hints.\n Effect.tap(() =>\n read(ref.objectType, ref.id).pipe(\n Effect.tap((value) => Effect.sync(() => install(value)))\n )\n )\n )\n ),\n () =>\n read(ref.objectType, ref.id).pipe(\n Effect.tap((value) => Effect.sync(() => install(value)))\n )\n ).pipe(\n Effect.scoped,\n Effect.tapError((error) =>\n Effect.sync(() => publish({ status: \"error\", error: error.message }))\n ),\n Effect.retry({ schedule: Schedule.spaced(1000), while: (error) => error.retryable }),\n Effect.catch((error) => Effect.logError(\"Connection watch stopped\", error)),\n Effect.forkScoped({ startImmediately: true })\n );\n // Supply a current value while background watch acquisition is pending;\n // the acquisition path repeats this read after registration.\n yield* read(ref.objectType, ref.id).pipe(\n Effect.tap((value) => Effect.sync(() => install(value)))\n );\n const monitor = {\n changes: Stream.callback<ConnectionState>(\n (queue) =>\n Effect.acquireRelease(\n Effect.sync(() => {\n const send = (next: ConnectionState) => {\n Queue.offerUnsafe(queue, next);\n };\n listeners.add(send);\n send(state);\n return send;\n }),\n (send) =>\n Effect.sync(() => {\n listeners.delete(send);\n })\n ),\n { bufferSize: 1, strategy: \"sliding\" }\n ),\n };\n const handlers = options.handlers ?? createDefaultConnectionEgressHandlers();\n const sockets = new Set<WebSocket>();\n const lifetime = new AbortController();\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => {\n listeners.clear();\n lifetime.abort();\n for (const socket of sockets) socket.close();\n sockets.clear();\n })\n );\n const acquired = yield* service.acquire({\n connection: { objectType: ref.objectType, value: row } as SavedConnection,\n serviceInstance,\n credential: currentCredential(),\n handlers: {\n fetch: (request) =>\n handlers.fetch(\n new Request(request, {\n signal: AbortSignal.any([request.signal, lifetime.signal]),\n })\n ),\n createWebSocket: Effect.fnUntraced(function* (\n url: string | URL,\n protocols?: string | string[]\n ) {\n const socket = yield* handlers.createWebSocket(url, protocols);\n if (lifetime.signal.aborted) {\n socket.close();\n return yield* unavailable(\"The selected connection was released.\");\n }\n sockets.add(socket);\n socket.addEventListener(\"close\", () => sockets.delete(socket), { once: true });\n return socket;\n }),\n },\n });\n const scope = yield* Effect.scope;\n const owned = <A>(work: Effect.Effect<A, BackendError>) =>\n Effect.suspend(() =>\n scope.state._tag === \"Closed\"\n ? Effect.fail(unavailable(\"The selected connection was released.\"))\n : Effect.acquireUseRelease(Effect.forkIn(work, scope), Fiber.join, Fiber.interrupt)\n );\n // Compare and persist in one transaction: a late rejection must neither\n // pause a newer login nor resurrect a disconnected row. The ordinary\n // journal/watch path also updates account queries.\n const markNeedsAuthentication = (observed: string | undefined) =>\n options.store\n .transaction(\n Effect.gen(function* () {\n const current = yield* options.store.get(ref.objectType, ref.id);\n if (current?.status === \"active\" && credentialVersion(current) === observed)\n yield* options.store.put(ref.objectType, {\n ...current,\n status: \"needs-auth\",\n });\n })\n )\n .pipe(\n Effect.mapError(connectBackendError),\n Effect.tapError((cause) =>\n Effect.logError(\"Could not save connection authentication status\", cause)\n ),\n Effect.ignore,\n Effect.uninterruptible\n );\n const failed = Effect.fnUntraced(function* (error: BackendError, observed: string | undefined) {\n if (isUnauthenticatedError(error)) yield* markNeedsAuthentication(observed);\n return yield* error;\n });\n // Check an expired external session with its service. Runs only inside `renew`.\n const verifyExternalSession: Effect.Effect<void, BackendError> = Effect.gen(function* () {\n const selected = yield* options.store.get(\"ExternalSessionConnection\", ref.id);\n if (\n !selected ||\n selected.status !== \"active\" ||\n !selected.expiresAt ||\n selected.expiresAt.epochMilliseconds > (yield* Clock.currentTimeMillis)\n )\n return;\n if (!service.externalSession)\n return yield* new BackendError({\n operation: \"connect.session.verify\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"This service cannot verify an external session.\",\n });\n (yield* CredentialObserver)(credentialVersion(selected));\n const verified = yield* Effect.result(\n service.externalSession({\n serviceInstance,\n sessionId: selected.sessionId,\n })\n );\n yield* options.store.transaction(\n Effect.gen(function* () {\n const latest = yield* options.store.get(\"ExternalSessionConnection\", ref.id);\n if (!latest || credentialVersion(latest) !== credentialVersion(selected)) return;\n if (verified._tag === \"Failure\") return yield* verified.failure;\n const identity = verified.success;\n if (\n identity.userId !== selected.userId ||\n (identity.expiresAt &&\n identity.expiresAt.epochMilliseconds <= (yield* Clock.currentTimeMillis))\n )\n return yield* connectError(\n \"NeedsAuthentication\",\n \"The selected external session requires authentication.\"\n );\n yield* options.store.put(\"ExternalSessionConnection\", {\n ...latest,\n title: identity.title ?? latest.title,\n expiresAt: identity.expiresAt,\n });\n })\n );\n }).pipe(\n Effect.mapError((error) =>\n error instanceof BackendError ? error : connectBackendError(error)\n )\n );\n const renewal = yield* Semaphore.make(1);\n // Renew the credential that was saved at `version`, once: concurrent rejections\n // of the same credential share one renewal, and a newer credential wins.\n // Rejections queued behind a renewal that failed share its failure instead of\n // each asking the provider again; a rejection after it tries again.\n let renewals = 0;\n let failedRenewal: { version: number; attempt: number; error: BackendError } | undefined;\n // `expiring` renews ahead of a rejection: an OAuth token about to expire, or an\n // external session whose saved expiry has passed.\n const renew = (version: number, reason: \"rejected\" | \"expiring\" = \"rejected\") =>\n Effect.suspend(() => {\n const waitingSince = renewals;\n return renewal.withPermit(\n Effect.gen(function* () {\n if (version !== credentialGeneration) return;\n if (failedRenewal?.version === version && failedRenewal.attempt > waitingSince)\n return yield* failedRenewal.error;\n const current = yield* read(ref.objectType, ref.id);\n if (current?.status !== \"active\") return;\n if (ref.objectType === \"ExternalSessionConnection\" && reason === \"expiring\") {\n const result = yield* Effect.result(verifyExternalSession);\n install(yield* read(ref.objectType, ref.id));\n // Whether the service rejected the session or could not check it,\n // that is the answer for every request queued on this check.\n if (result._tag === \"Failure\") {\n failedRenewal = { version, attempt: ++renewals, error: result.failure };\n return yield* result.failure;\n }\n renewals++;\n return;\n }\n if (ref.objectType !== \"OAuthConnection\") {\n yield* markNeedsAuthentication(credentialVersion(current));\n return;\n }\n const result = yield* Effect.result(\n backend.applyAction({\n id: crypto.randomUUID(),\n name: \"refreshConnection\",\n parameters: { connectionId: ref.id },\n })\n );\n // Publish now rather than when the row watch catches up, so a\n // concurrent rejection of the old credential does not renew again.\n install(yield* read(ref.objectType, ref.id));\n // A refresh token that no longer works already moved the\n // connection to needs-auth; anything else may succeed later.\n if (result._tag === \"Failure\" && !isUnauthenticatedError(result.failure)) {\n const error = renewalUnavailable(result.failure);\n failedRenewal = { version, attempt: ++renewals, error };\n return yield* error;\n }\n renewals++;\n })\n );\n });\n const requireAuthentication = Effect.fnUntraced(function* () {\n const current = yield* read(ref.objectType, ref.id);\n if (!current || current.status === \"inactive\")\n return yield* unavailable(\"The selected connection is disconnected.\");\n if (current.status !== \"active\")\n return yield* unavailable(\"The selected connection requires authentication.\");\n return current;\n });\n const egress: ConnectionEgress = {\n fetch: (input, init) =>\n owned(\n Effect.gen(function* () {\n const version = credentialGeneration;\n let observed = credentialVersion(yield* requireAuthentication());\n const request = yield* Effect.try({\n try: () => new Request(input, init),\n catch: (cause) => classifyBackendFailure(\"connect.egress.fetch\", cause),\n });\n // Only a request without a body is sent again after a renewal. A body\n // can be a one-shot stream (a proxied upload); the outbox or sync\n // retries those after the renewal instead.\n const replay = request.body === null ? request.clone() : undefined;\n const send = (value: Request) =>\n acquired.fetch(value).pipe(\n Effect.provideService(CredentialObserver, (value) => {\n observed = value;\n })\n );\n const first = yield* Effect.result(send(request));\n if (first._tag === \"Success\") return first.success;\n if (\n !isUnauthenticatedError(first.failure) ||\n ref.objectType !== \"OAuthConnection\"\n )\n return yield* failed(first.failure, observed);\n yield* renew(version);\n if (state.status !== \"active\") return yield* first.failure;\n if (!replay) return yield* retryAfterRenewal();\n observed = credentialVersion(yield* requireAuthentication());\n return yield* send(replay).pipe(Effect.catch((error) => failed(error, observed)));\n })\n ),\n createWebSocket: (url, protocols) =>\n owned(\n Effect.gen(function* () {\n let observed = credentialVersion(yield* requireAuthentication());\n return yield* acquired.createWebSocket(url, protocols).pipe(\n Effect.provideService(CredentialObserver, (value) => {\n observed = value;\n }),\n Effect.catch((error) => failed(error, observed))\n );\n })\n ),\n };\n const authentication: ConnectionLifecycle = {\n get state() {\n return state;\n },\n changes: monitor.changes,\n get credentialVersion() {\n return credentialGeneration;\n },\n refresh: renew,\n };\n return {\n connection: ref,\n userId: row.userId,\n serviceInstance: serviceInstance as ServiceInstanceRecord,\n egress,\n authentication,\n } satisfies ConnectionAccess;\n }),\n });\n return {\n acquire: (connection: ConnectionRef) => RcMap.get(access, Schema.encodeSync(codec)(connection)),\n };\n});\n"],"mappings":";;;;;;;;;AA+BA,MAAM,eAAe,YACjB,IAAI,aAAa;CACb,WAAW;CACX,MAAM;CACN,WAAW;CACX;AACJ,CAAC;AAIL,MAAM,qBAAqB,QAAQ,UAC/B,2CACA,EAAE,0BAA0B,CAAC,EAAE,CACnC;AACA,MAAM,0BACF,IAAI,aAAa;CACb,WAAW;CACX,MAAM;CACN,WAAW;CACX,eAAe;CACf,SAAS;AACb,CAAC;AACL,MAAM,sBAAsB,UACxB,IAAI,aAAa;CACb,WAAW;CACX,MAAM;CACN,WAAW;CACX,eAAe;CACf,SAAS;CACT;AACJ,CAAC;;;;AAKL,MAAa,yBAAyB,OAAO,GAAG,qBAAqB,CAAC,CAAC,WAAW,SAK/E;CACC,MAAM,UAAU,QAAQ;CACxB,MAAM,WAAW,IAAI,IAAI,QAAQ,SAAS,KAAK,YAAY,CAAC,QAAQ,SAAS,OAAO,CAAC,CAAC;CACtF,IAAI,SAAS,SAAS,QAAQ,SAAS,QACnC,OAAO,OAAO,IAAI,aAAa;EAC3B,W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,CAAC,CAAC;GACpF,CAAC,CACL;GACJ,kBAAkB,KAAK,cACnB,MACI,OAAO,IAAI,aAAa;IACpB,IAAI,WAAW,kBAAkB,OAAO,sBAAsB,CAAC;IAC/D,OAAO,OAAO,SAAS,gBAAgB,KAAK,SAAS,CAAC,CAAC,KACnD,OAAO,eAAe,qBAAqB,UAAU;KACjD,WAAW;IACf,CAAC,GACD,OAAO,OAAO,UAAU,OAAO,OAAO,QAAQ,CAAC,CACnD;GACJ,CAAC,CACL;EACR;EACA,MAAM,iBAAsC;GACxC,IAAI,QAAQ;IACR,OAAO;GACX;GACA,SAAS,QAAQ;GACjB,IAAI,oBAAoB;IACpB,OAAO;GACX;GACA,SAAS;EACb;EACA,OAAO;GACH,YAAY;GACZ,QAAQ,IAAI;GACK;GACjB;GACA;EACJ;CACJ,CAAC,EACL,CAAC;CACD,OAAO,EACH,UAAU,eAA8B,MAAM,IAAI,QAAQ,OAAO,WAAW,KAAK,CAAC,CAAC,UAAU,CAAC,EAClG;AACJ,CAAC"}
|
|
1
|
+
{"version":3,"file":"serviceConnections.js","names":[],"sources":["../src/serviceConnections.ts"],"sourcesContent":["import { BackendError, classifyBackendFailure, isUnauthenticatedError } from \"@party-stack/ontology-backend\";\nimport * as q from \"@party-stack/ontology-spec/query\";\nimport { Clock, Context, Effect, Fiber, Queue, RcMap, Schema, Stream, Schedule, Semaphore } from \"effect\";\nimport { accessTokenNeedsRefresh, connectionAccessToken } from \"./core/accessToken.js\";\nimport { connectBackendError } from \"./core/backend.js\";\nimport { connectError } from \"./core/errors.js\";\nimport { createDefaultConnectionEgressHandlers } from \"./createDefaultConnectionEgressHandlers.js\";\nimport { connectOntology } from \"./spec/index.js\";\nimport type { ConnectStore } from \"./core/store.js\";\nimport type { ConnectionRef, SavedConnection, ServiceConnector } from \"./ServiceConnector.js\";\nimport type { ConnectOntology, ServiceInstanceRecord } from \"./spec/index.js\";\nimport type {\n ConnectionEgress,\n ConnectionEgressHandlers,\n ConnectionLifecycle,\n ConnectionState,\n} from \"./types.js\";\nimport type { OntologyBackendService } from \"@party-stack/ontology-backend\";\n\n/** Scoped identity and egress for one saved connection. Cached data can reopen\n * while authentication is required; actual egress always requires active credentials.\n */\nexport interface ConnectionAccess {\n readonly connection: ConnectionRef;\n readonly userId: string;\n readonly serviceInstance: ServiceInstanceRecord;\n readonly egress: ConnectionEgress;\n /** Pass to the replica that syncs this connection; show apps only its monitor fields. */\n readonly authentication: ConnectionLifecycle;\n}\n\nconst unavailable = (message: string) =>\n new BackendError({\n operation: \"connect.acquire\",\n kind: \"Unauthenticated\",\n retryable: false,\n message,\n });\n\n// Observe the credential actually used by this request, including renewal. A\n// later rejection must not change the status of a newer saved session.\nconst CredentialObserver = Context.Reference<(version: string) => void>(\n \"@party-stack/connect/CredentialObserver\",\n { defaultValue: () => () => {} }\n);\nconst retryAfterRenewal = () =>\n new BackendError({\n operation: \"connect.egress\",\n kind: \"Unavailable\",\n retryable: true,\n actionOutcome: \"not-committed\",\n message: \"The credential was renewed after the service rejected it; retry the request.\",\n });\nconst renewalUnavailable = (cause: BackendError) =>\n new BackendError({\n operation: \"connect.refresh\",\n kind: \"Unavailable\",\n retryable: true,\n actionOutcome: \"not-committed\",\n message: \"The credential could not be renewed yet; retry the request.\",\n cause,\n });\n\n/** Acquire saved identity and egress from ontology records. The map holds only\n * scoped access; the Connect backend remains the sole durable inventory.\n */\nexport const makeServiceConnections = Effect.fn(\"Connect.connections\")(function* (options: {\n readonly backend: OntologyBackendService;\n readonly store: ConnectStore;\n readonly services: readonly ServiceConnector[];\n readonly handlers?: ConnectionEgressHandlers;\n}) {\n const backend = options.backend;\n const services = new Map(options.services.map((service) => [service.service, service]));\n if (services.size !== options.services.length)\n return yield* new BackendError({\n operation: \"connect.configure\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"Service connector names must be unique.\",\n });\n const read = Effect.fnUntraced(function* <N extends keyof ConnectOntology[\"objectTypes\"]>(\n objectType: N,\n id: string\n ) {\n const rows = yield* backend.query({\n select: [\n q.sub(\"rows\", {\n from: { source: { objectType }, binding: \"row\" },\n where: q.eq(q.field(\"row\", \"id\"), q.literal(id)),\n select: connectOntology.objectTypes\n .find((type) => type.name === objectType)!\n .properties.map((property) =>\n q.selectField(property.name, q.field(\"row\", property.name))\n ),\n }),\n ],\n });\n return (rows.rows as ConnectOntology[\"objectTypes\"][N][])[0];\n });\n const reference = Schema.Struct({\n objectType: Schema.Literals([\"OAuthConnection\", \"ApiKeyConnection\", \"ExternalSessionConnection\"]),\n id: Schema.NonEmptyString,\n });\n const codec = Schema.fromJsonString(reference);\n const access = yield* RcMap.make({\n lookup: Effect.fnUntraced(function* (key: string) {\n const ref = yield* Schema.decodeUnknownEffect(codec)(key).pipe(\n Effect.mapError((cause) => classifyBackendFailure(\"connect.acquire\", cause))\n );\n const row = yield* read(ref.objectType, ref.id);\n if (!row || row.status === \"inactive\" || !row.userId)\n return yield* unavailable(\"The selected connection is disconnected.\");\n const instanceId =\n ref.objectType === \"OAuthConnection\"\n ? (yield* read(\n \"OAuthApplication\",\n (row as ConnectOntology[\"objectTypes\"][\"OAuthConnection\"]).application\n ))?.serviceInstance\n : (\n row as\n | ConnectOntology[\"objectTypes\"][\"ApiKeyConnection\"]\n | ConnectOntology[\"objectTypes\"][\"ExternalSessionConnection\"]\n ).serviceInstance;\n const serviceInstance = instanceId ? yield* read(\"ServiceInstance\", instanceId) : undefined;\n if (!serviceInstance)\n return yield* new BackendError({\n operation: \"connect.acquire\",\n kind: \"NotFound\",\n retryable: false,\n message: \"Service instance is unavailable.\",\n });\n const service = services.get(serviceInstance.service);\n if (!service)\n return yield* new BackendError({\n operation: \"connect.acquire\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"Service connector is unavailable.\",\n });\n const currentCredential = Effect.fnUntraced(function* (\n renewEarly = true\n ): Effect.fn.Return<string, BackendError> {\n const current = yield* read(ref.objectType, ref.id);\n if (!current || current.status === \"inactive\")\n return yield* unavailable(\"The selected connection is disconnected.\");\n if (current.status !== \"active\")\n return yield* unavailable(\"The selected connection requires authentication.\");\n if (ref.objectType === \"OAuthConnection\") {\n if (\n renewEarly &&\n accessTokenNeedsRefresh(\n current as ConnectOntology[\"objectTypes\"][\"OAuthConnection\"],\n yield* Clock.currentTimeMillis\n )\n ) {\n // Renew a token that is about to expire through the connection's one\n // renewal, like a rejected one. Requests queued behind it skip their own\n // refresh once the credential changes, even when the new token is also\n // short-lived, and share a failed attempt instead of each retrying it.\n yield* renew(credentialGeneration);\n return yield* currentCredential(false);\n }\n // This manager owns renewal; the helper only reads and decrypts.\n return yield* connectionAccessToken(backend, ref.id, { refresh: false });\n }\n const expiresAt = (\n current as\n | ConnectOntology[\"objectTypes\"][\"ExternalSessionConnection\"]\n | ConnectOntology[\"objectTypes\"][\"ApiKeyConnection\"]\n ).expiresAt;\n if (ref.objectType === \"ExternalSessionConnection\") {\n (yield* CredentialObserver)(credentialVersion(current));\n if (expiresAt && expiresAt.epochMilliseconds <= (yield* Clock.currentTimeMillis)) {\n // Verify through the connection's one renewal: requests that queued for\n // the same expired session share its answer instead of each asking again.\n yield* renew(credentialGeneration, \"expiring\");\n return yield* currentCredential();\n }\n return (current as ConnectOntology[\"objectTypes\"][\"ExternalSessionConnection\"]).sessionId;\n }\n if (expiresAt && expiresAt.epochMilliseconds <= (yield* Clock.currentTimeMillis))\n return yield* unavailable(\"The selected connection has expired.\");\n const apiKey = (current as ConnectOntology[\"objectTypes\"][\"ApiKeyConnection\"]).apiKey;\n if (!apiKey || !backend.encrypted) return yield* unavailable(\"API key is unavailable.\");\n const result = yield* backend.encrypted.decrypt({\n ...apiKey,\n source: { objectType: ref.objectType, primaryKey: ref.id, property: \"apiKey\" },\n });\n return yield* Schema.decodeUnknownEffect(Schema.String)(result.value).pipe(\n Effect.mapError((cause) => classifyBackendFailure(\"connect.credential\", cause))\n );\n });\n let state: ConnectionState = { status: row.status };\n let fingerprint = JSON.stringify(row);\n const credentialVersion = (value: typeof row | undefined) =>\n JSON.stringify(\n !value\n ? null\n : [\n value.status,\n value.userId,\n \"application\" in value\n ? [\n value.application,\n value.accessToken?.ciphertext,\n value.refreshToken?.ciphertext,\n value.operationId,\n ]\n : \"sessionId\" in value\n ? [value.serviceInstance, value.sessionId, value.expiresAt]\n : [value.serviceInstance, value.apiKey?.ciphertext, value.expiresAt],\n ]\n );\n const listeners = new Set<(state: ConnectionState) => void>();\n const publish = (value: ConnectionState, changedCredential = false) => {\n if (!changedCredential && JSON.stringify(state) === JSON.stringify(value)) return;\n state = value;\n for (const listener of listeners) listener(value);\n };\n // The credential itself, not bookkeeping such as an in-progress refresh marker:\n // only a new credential (or a status change) is a new activation.\n const credentialIdentity = (value: typeof row | undefined) =>\n JSON.stringify(\n !value\n ? null\n : [\n value.status,\n value.userId,\n \"application\" in value\n ? value.accessToken?.ciphertext\n : \"sessionId\" in value\n ? [value.sessionId, value.expiresAt]\n : [value.apiKey?.ciphertext, value.expiresAt],\n ]\n );\n let credentialGeneration = 0;\n let credential = credentialIdentity(row);\n const install = (value: typeof row | undefined) => {\n const next = JSON.stringify(value);\n const changed = fingerprint !== next;\n fingerprint = next;\n const nextCredential = credentialIdentity(value);\n const renewed = nextCredential !== credential;\n credential = nextCredential;\n if (renewed) credentialGeneration++;\n if (changed || state.status === \"error\")\n publish(\n value?.status === \"needs-auth\" && value.statusReason\n ? { status: \"needs-auth\", error: value.statusReason }\n : { status: value?.status ?? \"inactive\" },\n renewed\n );\n };\n const watch =\n backend.changes?.watch ??\n backend.watchSubset?.({\n from: { source: { objectType: ref.objectType }, binding: \"connection\" },\n where: q.eq(q.field(\"connection\", \"id\"), q.literal(ref.id)),\n });\n if (watch)\n yield* Stream.runForEach(\n Stream.unwrap(\n watch.pipe(\n // Acquisition has registered and buffered the feed. Re-read\n // after every acquisition, including a retry, before consuming hints.\n Effect.tap(() =>\n read(ref.objectType, ref.id).pipe(\n Effect.tap((value) => Effect.sync(() => install(value)))\n )\n )\n )\n ),\n () =>\n read(ref.objectType, ref.id).pipe(\n Effect.tap((value) => Effect.sync(() => install(value)))\n )\n ).pipe(\n Effect.scoped,\n Effect.tapError((error) =>\n Effect.sync(() => publish({ status: \"error\", error: error.message }))\n ),\n Effect.retry({ schedule: Schedule.spaced(1000), while: (error) => error.retryable }),\n Effect.catch((error) => Effect.logError(\"Connection watch stopped\", error)),\n Effect.forkScoped({ startImmediately: true })\n );\n // Supply a current value while background watch acquisition is pending;\n // the acquisition path repeats this read after registration.\n yield* read(ref.objectType, ref.id).pipe(\n Effect.tap((value) => Effect.sync(() => install(value)))\n );\n const monitor = {\n changes: Stream.callback<ConnectionState>(\n (queue) =>\n Effect.acquireRelease(\n Effect.sync(() => {\n const send = (next: ConnectionState) => {\n Queue.offerUnsafe(queue, next);\n };\n listeners.add(send);\n send(state);\n return send;\n }),\n (send) =>\n Effect.sync(() => {\n listeners.delete(send);\n })\n ),\n { bufferSize: 1, strategy: \"sliding\" }\n ),\n };\n const handlers = options.handlers ?? createDefaultConnectionEgressHandlers();\n const sockets = new Set<WebSocket>();\n const lifetime = new AbortController();\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => {\n listeners.clear();\n lifetime.abort();\n for (const socket of sockets) socket.close();\n sockets.clear();\n })\n );\n const acquired = yield* service.acquire({\n connection: { objectType: ref.objectType, value: row } as SavedConnection,\n serviceInstance,\n credential: currentCredential(),\n handlers: {\n fetch: (request) =>\n handlers.fetch(\n new Request(request, {\n signal: AbortSignal.any([request.signal, lifetime.signal]),\n })\n ),\n createWebSocket: Effect.fnUntraced(function* (\n url: string | URL,\n protocols?: string | string[]\n ) {\n const socket = yield* handlers.createWebSocket(url, protocols);\n if (lifetime.signal.aborted) {\n socket.close();\n return yield* unavailable(\"The selected connection was released.\");\n }\n sockets.add(socket);\n socket.addEventListener(\"close\", () => sockets.delete(socket), { once: true });\n return socket;\n }),\n },\n });\n const scope = yield* Effect.scope;\n const owned = <A>(work: Effect.Effect<A, BackendError>) =>\n Effect.suspend(() =>\n scope.state._tag === \"Closed\"\n ? Effect.fail(unavailable(\"The selected connection was released.\"))\n : Effect.acquireUseRelease(Effect.forkIn(work, scope), Fiber.join, Fiber.interrupt)\n );\n // Compare and persist in one transaction: a late rejection must neither\n // pause a newer login nor resurrect a disconnected row. The ordinary\n // journal/watch path also updates account queries.\n const markNeedsAuthentication = (observed: string | undefined, reason: string) =>\n options.store\n .transaction(\n Effect.gen(function* () {\n const current = yield* options.store.get(ref.objectType, ref.id);\n if (current?.status !== \"active\" || credentialVersion(current) !== observed)\n return;\n yield* options.store.put(ref.objectType, {\n ...current,\n status: \"needs-auth\",\n statusReason: reason,\n });\n yield* Effect.logWarning(\"Connection needs a sign-in\", {\n connection: ref.id,\n reason,\n });\n })\n )\n .pipe(\n Effect.mapError(connectBackendError),\n Effect.tapError((cause) =>\n Effect.logError(\"Could not save connection authentication status\", cause)\n ),\n Effect.ignore,\n Effect.uninterruptible\n );\n const failed = Effect.fnUntraced(function* (error: BackendError, observed: string | undefined) {\n if (isUnauthenticatedError(error))\n yield* markNeedsAuthentication(\n observed,\n \"The service rejected the saved credentials. \" + error.message\n );\n return yield* error;\n });\n // Check an expired external session with its service. Runs only inside `renew`.\n const verifyExternalSession: Effect.Effect<void, BackendError> = Effect.gen(function* () {\n const selected = yield* options.store.get(\"ExternalSessionConnection\", ref.id);\n if (\n !selected ||\n selected.status !== \"active\" ||\n !selected.expiresAt ||\n selected.expiresAt.epochMilliseconds > (yield* Clock.currentTimeMillis)\n )\n return;\n if (!service.externalSession)\n return yield* new BackendError({\n operation: \"connect.session.verify\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"This service cannot verify an external session.\",\n });\n (yield* CredentialObserver)(credentialVersion(selected));\n const verified = yield* Effect.result(\n service.externalSession({\n serviceInstance,\n sessionId: selected.sessionId,\n })\n );\n yield* options.store.transaction(\n Effect.gen(function* () {\n const latest = yield* options.store.get(\"ExternalSessionConnection\", ref.id);\n if (!latest || credentialVersion(latest) !== credentialVersion(selected)) return;\n if (verified._tag === \"Failure\") return yield* verified.failure;\n const identity = verified.success;\n if (\n identity.userId !== selected.userId ||\n (identity.expiresAt &&\n identity.expiresAt.epochMilliseconds <= (yield* Clock.currentTimeMillis))\n )\n return yield* connectError(\n \"NeedsAuthentication\",\n \"The selected external session requires authentication.\"\n );\n yield* options.store.put(\"ExternalSessionConnection\", {\n ...latest,\n title: identity.title ?? latest.title,\n expiresAt: identity.expiresAt,\n });\n })\n );\n }).pipe(\n Effect.mapError((error) =>\n error instanceof BackendError ? error : connectBackendError(error)\n )\n );\n const renewal = yield* Semaphore.make(1);\n // Renew the credential that was saved at `version`, once: concurrent rejections\n // of the same credential share one renewal, and a newer credential wins.\n // Rejections queued behind a renewal that failed share its failure instead of\n // each asking the provider again; a rejection after it tries again.\n let renewals = 0;\n let failedRenewal: { version: number; attempt: number; error: BackendError } | undefined;\n // `expiring` renews ahead of a rejection: an OAuth token about to expire, or an\n // external session whose saved expiry has passed.\n const renew = (version: number, reason: \"rejected\" | \"expiring\" = \"rejected\") =>\n Effect.suspend(() => {\n const waitingSince = renewals;\n return renewal.withPermit(\n Effect.gen(function* () {\n if (version !== credentialGeneration) return;\n if (failedRenewal?.version === version && failedRenewal.attempt > waitingSince)\n return yield* failedRenewal.error;\n const current = yield* read(ref.objectType, ref.id);\n if (current?.status !== \"active\") return;\n if (ref.objectType === \"ExternalSessionConnection\" && reason === \"expiring\") {\n const result = yield* Effect.result(verifyExternalSession);\n install(yield* read(ref.objectType, ref.id));\n // Whether the service rejected the session or could not check it,\n // that is the answer for every request queued on this check.\n if (result._tag === \"Failure\") {\n failedRenewal = { version, attempt: ++renewals, error: result.failure };\n return yield* result.failure;\n }\n renewals++;\n return;\n }\n if (ref.objectType !== \"OAuthConnection\") {\n yield* markNeedsAuthentication(\n credentialVersion(current),\n \"The service rejected the saved credentials, and they cannot be renewed.\"\n );\n return;\n }\n const result = yield* Effect.result(\n backend.applyAction({\n id: crypto.randomUUID(),\n name: \"refreshConnection\",\n parameters: { connectionId: ref.id },\n })\n );\n // Publish now rather than when the row watch catches up, so a\n // concurrent rejection of the old credential does not renew again.\n install(yield* read(ref.objectType, ref.id));\n // A refresh token that no longer works already moved the\n // connection to needs-auth; anything else may succeed later.\n if (result._tag === \"Failure\" && !isUnauthenticatedError(result.failure)) {\n const error = renewalUnavailable(result.failure);\n failedRenewal = { version, attempt: ++renewals, error };\n return yield* error;\n }\n renewals++;\n })\n );\n });\n const requireAuthentication = Effect.fnUntraced(function* () {\n const current = yield* read(ref.objectType, ref.id);\n if (!current || current.status === \"inactive\")\n return yield* unavailable(\"The selected connection is disconnected.\");\n if (current.status !== \"active\")\n return yield* unavailable(\"The selected connection requires authentication.\");\n return current;\n });\n const egress: ConnectionEgress = {\n fetch: (input, init) =>\n owned(\n Effect.gen(function* () {\n const version = credentialGeneration;\n let observed = credentialVersion(yield* requireAuthentication());\n const request = yield* Effect.try({\n try: () => new Request(input, init),\n catch: (cause) => classifyBackendFailure(\"connect.egress.fetch\", cause),\n });\n // Only a request without a body is sent again after a renewal. A body\n // can be a one-shot stream (a proxied upload); the outbox or sync\n // retries those after the renewal instead.\n const replay = request.body === null ? request.clone() : undefined;\n const send = (value: Request) =>\n acquired.fetch(value).pipe(\n Effect.provideService(CredentialObserver, (value) => {\n observed = value;\n })\n );\n const first = yield* Effect.result(send(request));\n if (first._tag === \"Success\") return first.success;\n if (\n !isUnauthenticatedError(first.failure) ||\n ref.objectType !== \"OAuthConnection\"\n )\n return yield* failed(first.failure, observed);\n yield* renew(version);\n if (state.status !== \"active\") return yield* first.failure;\n if (!replay) return yield* retryAfterRenewal();\n observed = credentialVersion(yield* requireAuthentication());\n return yield* send(replay).pipe(Effect.catch((error) => failed(error, observed)));\n })\n ),\n createWebSocket: (url, protocols) =>\n owned(\n Effect.gen(function* () {\n let observed = credentialVersion(yield* requireAuthentication());\n return yield* acquired.createWebSocket(url, protocols).pipe(\n Effect.provideService(CredentialObserver, (value) => {\n observed = value;\n }),\n Effect.catch((error) => failed(error, observed))\n );\n })\n ),\n };\n const authentication: ConnectionLifecycle = {\n get state() {\n return state;\n },\n changes: monitor.changes,\n get credentialVersion() {\n return credentialGeneration;\n },\n refresh: renew,\n };\n return {\n connection: ref,\n userId: row.userId,\n serviceInstance: serviceInstance as ServiceInstanceRecord,\n egress,\n authentication,\n } satisfies ConnectionAccess;\n }),\n });\n return {\n acquire: (connection: ConnectionRef) => RcMap.get(access, Schema.encodeSync(codec)(connection)),\n };\n});\n"],"mappings":";;;;;;;;;AA+BA,MAAM,eAAe,YACjB,IAAI,aAAa;CACb,WAAW;CACX,MAAM;CACN,WAAW;CACX;AACJ,CAAC;AAIL,MAAM,qBAAqB,QAAQ,UAC/B,2CACA,EAAE,0BAA0B,CAAC,EAAE,CACnC;AACA,MAAM,0BACF,IAAI,aAAa;CACb,WAAW;CACX,MAAM;CACN,WAAW;CACX,eAAe;CACf,SAAS;AACb,CAAC;AACL,MAAM,sBAAsB,UACxB,IAAI,aAAa;CACb,WAAW;CACX,MAAM;CACN,WAAW;CACX,eAAe;CACf,SAAS;CACT;AACJ,CAAC;;;;AAKL,MAAa,yBAAyB,OAAO,GAAG,qBAAqB,CAAC,CAAC,WAAW,SAK/E;CACC,MAAM,UAAU,QAAQ;CACxB,MAAM,WAAW,IAAI,IAAI,QAAQ,SAAS,KAAK,YAAY,CAAC,QAAQ,SAAS,OAAO,CAAC,CAAC;CACtF,IAAI,SAAS,SAAS,QAAQ,SAAS,QACnC,OAAO,OAAO,IAAI,aAAa;EAC3B,WAAW;EACX,MAAM;EACN,WAAW;EACX,SAAS;CACb,CAAC;CACL,MAAM,OAAO,OAAO,WAAW,WAC3B,YACA,IACF;EAcE,QAAQ,OAbY,QAAQ,MAAM,EAC9B,QAAQ,CACJ,EAAE,IAAI,QAAQ;GACV,MAAM;IAAE,QAAQ,EAAE,WAAW;IAAG,SAAS;GAAM;GAC/C,OAAO,EAAE,GAAG,EAAE,MAAM,OAAO,IAAI,GAAG,EAAE,QAAQ,EAAE,CAAC;GAC/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,CAAC;IAC/D,OAAO,OAAO,SAAS,gBAAgB,KAAK,SAAS,CAAC,CAAC,KACnD,OAAO,eAAe,qBAAqB,UAAU;KACjD,WAAW;IACf,CAAC,GACD,OAAO,OAAO,UAAU,OAAO,OAAO,QAAQ,CAAC,CACnD;GACJ,CAAC,CACL;EACR;EACA,MAAM,iBAAsC;GACxC,IAAI,QAAQ;IACR,OAAO;GACX;GACA,SAAS,QAAQ;GACjB,IAAI,oBAAoB;IACpB,OAAO;GACX;GACA,SAAS;EACb;EACA,OAAO;GACH,YAAY;GACZ,QAAQ,IAAI;GACK;GACjB;GACA;EACJ;CACJ,CAAC,EACL,CAAC;CACD,OAAO,EACH,UAAU,eAA8B,MAAM,IAAI,QAAQ,OAAO,WAAW,KAAK,CAAC,CAAC,UAAU,CAAC,EAClG;AACJ,CAAC"}
|
package/lib/spec/index.d.ts
CHANGED
|
@@ -230,6 +230,19 @@ export declare const connectOntology: {
|
|
|
230
230
|
};
|
|
231
231
|
};
|
|
232
232
|
};
|
|
233
|
+
} | {
|
|
234
|
+
name: "statusReason";
|
|
235
|
+
displayName: "Status reason";
|
|
236
|
+
description: "Why the connection needs a sign-in, when known.";
|
|
237
|
+
type: {
|
|
238
|
+
kind: "optional";
|
|
239
|
+
value: {
|
|
240
|
+
type: {
|
|
241
|
+
kind: "string";
|
|
242
|
+
value: {};
|
|
243
|
+
};
|
|
244
|
+
};
|
|
245
|
+
};
|
|
233
246
|
} | {
|
|
234
247
|
name: "accessToken";
|
|
235
248
|
displayName: "Access token";
|
|
@@ -383,6 +396,19 @@ export declare const connectOntology: {
|
|
|
383
396
|
};
|
|
384
397
|
};
|
|
385
398
|
};
|
|
399
|
+
} | {
|
|
400
|
+
name: "statusReason";
|
|
401
|
+
displayName: "Status reason";
|
|
402
|
+
description: "Why the connection needs a sign-in, when known.";
|
|
403
|
+
type: {
|
|
404
|
+
kind: "optional";
|
|
405
|
+
value: {
|
|
406
|
+
type: {
|
|
407
|
+
kind: "string";
|
|
408
|
+
value: {};
|
|
409
|
+
};
|
|
410
|
+
};
|
|
411
|
+
};
|
|
386
412
|
} | {
|
|
387
413
|
name: "apiKey";
|
|
388
414
|
displayName: "API key";
|
|
@@ -471,6 +497,19 @@ export declare const connectOntology: {
|
|
|
471
497
|
};
|
|
472
498
|
};
|
|
473
499
|
};
|
|
500
|
+
} | {
|
|
501
|
+
name: "statusReason";
|
|
502
|
+
displayName: "Status reason";
|
|
503
|
+
description: "Why the connection needs a sign-in, when known.";
|
|
504
|
+
type: {
|
|
505
|
+
kind: "optional";
|
|
506
|
+
value: {
|
|
507
|
+
type: {
|
|
508
|
+
kind: "string";
|
|
509
|
+
value: {};
|
|
510
|
+
};
|
|
511
|
+
};
|
|
512
|
+
};
|
|
474
513
|
} | {
|
|
475
514
|
name: "sessionId";
|
|
476
515
|
displayName: "Session id";
|
package/lib/spec/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/spec/index.ts"],"mappings":";;;;;qBAKa
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/spec/index.ts"],"mappings":";;;;;qBAKa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAmeD,kBAAkB,aAAa;YAC/B,wBAAwB;YACxB,yBAAyB;YACzB,wBAAwB;YACxB,yBAAyB;YACzB,kCAAkC;YAClC,kCAAkC"}
|
package/lib/spec/index.js
CHANGED
|
@@ -142,6 +142,12 @@ const connectOntology = defineOntology({
|
|
|
142
142
|
}
|
|
143
143
|
] }) })
|
|
144
144
|
},
|
|
145
|
+
{
|
|
146
|
+
name: "statusReason",
|
|
147
|
+
displayName: "Status reason",
|
|
148
|
+
description: "Why the connection needs a sign-in, when known.",
|
|
149
|
+
type: o.optional({ type: o.string({}) })
|
|
150
|
+
},
|
|
145
151
|
{
|
|
146
152
|
name: "accessToken",
|
|
147
153
|
displayName: "Access token",
|
|
@@ -223,6 +229,12 @@ const connectOntology = defineOntology({
|
|
|
223
229
|
}
|
|
224
230
|
] }) })
|
|
225
231
|
},
|
|
232
|
+
{
|
|
233
|
+
name: "statusReason",
|
|
234
|
+
displayName: "Status reason",
|
|
235
|
+
description: "Why the connection needs a sign-in, when known.",
|
|
236
|
+
type: o.optional({ type: o.string({}) })
|
|
237
|
+
},
|
|
226
238
|
{
|
|
227
239
|
name: "apiKey",
|
|
228
240
|
displayName: "API key",
|
|
@@ -279,6 +291,12 @@ const connectOntology = defineOntology({
|
|
|
279
291
|
}
|
|
280
292
|
] }) })
|
|
281
293
|
},
|
|
294
|
+
{
|
|
295
|
+
name: "statusReason",
|
|
296
|
+
displayName: "Status reason",
|
|
297
|
+
description: "Why the connection needs a sign-in, when known.",
|
|
298
|
+
type: o.optional({ type: o.string({}) })
|
|
299
|
+
},
|
|
282
300
|
{
|
|
283
301
|
name: "sessionId",
|
|
284
302
|
displayName: "Session id",
|
package/lib/spec/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/spec/index.ts"],"sourcesContent":["import { defineOntology, o, type Infer } from \"@party-stack/ontology-spec\";\n\n/** Portable definitions. Applications may add properties/links before compiling them.\n * Connection and attempt instances are private to the credential authority.\n */\nexport const connectOntology = defineOntology({\n types: [],\n objectTypes: [\n {\n name: \"ServiceInstance\",\n pluralDisplayName: \"Service instances\",\n displayName: \"Service instance\",\n primaryKey: \"id\",\n properties: [\n { name: \"id\", displayName: \"Id\", type: o.string({}) },\n { name: \"title\", displayName: \"Title\", type: o.string({}) },\n { name: \"service\", displayName: \"Service\", type: o.string({}) },\n { name: \"instanceUrl\", displayName: \"Instance url\", type: o.string({}) },\n ],\n },\n {\n name: \"OAuthApplication\",\n pluralDisplayName: \"OAuthApplications\",\n displayName: \"OAuth application\",\n primaryKey: \"id\",\n properties: [\n { name: \"id\", displayName: \"Id\", type: o.string({}) },\n { name: \"title\", displayName: \"Title\", type: o.string({}) },\n {\n name: \"serviceInstance\",\n displayName: \"Service instance\",\n type: o.objectReference({ objectType: \"ServiceInstance\" }),\n },\n {\n name: \"flow\",\n displayName: \"Flow\",\n type: o.string({\n constraint: o.StringConstraint.enum({\n options: [\n { value: \"authorization-code\", label: \"authorization-code\" },\n { value: \"client-credentials\", label: \"client-credentials\" },\n ],\n }),\n }),\n },\n { name: \"clientId\", displayName: \"Client id\", type: o.string({}) },\n {\n name: \"scopes\",\n displayName: \"Requested scopes\",\n type: o.optional({ type: o.list({ elementType: o.string({}) }) }),\n },\n {\n name: \"redirectUrl\",\n displayName: \"Redirect URL\",\n type: o.optional({ type: o.string({}) }),\n },\n {\n name: \"clientSecret\",\n displayName: \"Client secret\",\n type: o.optional({ type: o.encrypted({ type: o.string({}) }) }),\n },\n {\n name: \"serviceAppId\",\n displayName: \"Service app id\",\n type: o.optional({ type: o.string({}) }),\n },\n {\n name: \"connection\",\n displayName: \"Connection\",\n type: o.optional({ type: o.objectReference({ objectType: \"OAuthConnection\" }) }),\n },\n ],\n },\n {\n name: \"OAuthConnection\",\n pluralDisplayName: \"OAuthConnections\",\n displayName: \"OAuth connection\",\n primaryKey: \"id\",\n properties: [\n { name: \"id\", displayName: \"Id\", type: o.string({}) },\n { name: \"title\", displayName: \"Title\", type: o.string({}) },\n {\n name: \"application\",\n displayName: \"Application\",\n type: o.objectReference({ objectType: \"OAuthApplication\" }),\n },\n {\n name: \"userId\",\n displayName: \"User id\",\n type: o.optional({ type: o.string({}) }),\n },\n {\n name: \"status\",\n displayName: \"Status\",\n type: o.string({\n constraint: o.StringConstraint.enum({\n options: [\n { value: \"active\", label: \"active\" },\n { value: \"needs-auth\", label: \"needs-auth\" },\n { value: \"inactive\", label: \"inactive\" },\n ],\n }),\n }),\n },\n {\n name: \"accessToken\",\n displayName: \"Access token\",\n type: o.optional({ type: o.encrypted({ type: o.string({}) }) }),\n },\n {\n name: \"accessTokenExpiresAt\",\n displayName: \"Access token expires at\",\n type: o.optional({ type: o.timestamp({}) }),\n },\n {\n name: \"refreshToken\",\n displayName: \"Refresh token\",\n type: o.optional({ type: o.encrypted({ type: o.string({}) }) }),\n },\n {\n name: \"refreshTokenExpiresAt\",\n displayName: \"Refresh token expires at\",\n type: o.optional({ type: o.timestamp({}) }),\n },\n {\n name: \"grantedScopes\",\n displayName: \"Granted scopes\",\n type: o.optional({ type: o.string({}) }),\n },\n {\n name: \"operationId\",\n displayName: \"Operation id\",\n type: o.optional({ type: o.string({}) }),\n },\n {\n name: \"operationExpiresAt\",\n displayName: \"Operation expires at\",\n type: o.optional({ type: o.timestamp({}) }),\n },\n ],\n },\n {\n name: \"ApiKeyConnection\",\n pluralDisplayName: \"API key connections\",\n displayName: \"API key connection\",\n primaryKey: \"id\",\n properties: [\n { name: \"id\", displayName: \"Id\", type: o.string({}) },\n { name: \"title\", displayName: \"Title\", type: o.string({}) },\n {\n name: \"serviceInstance\",\n displayName: \"Service instance\",\n type: o.objectReference({ objectType: \"ServiceInstance\" }),\n },\n { name: \"userId\", displayName: \"User id\", type: o.string({}) },\n {\n name: \"status\",\n displayName: \"Status\",\n type: o.string({\n constraint: o.StringConstraint.enum({\n options: [\n { value: \"active\", label: \"Active\" },\n { value: \"needs-auth\", label: \"Needs authentication\" },\n { value: \"inactive\", label: \"Inactive\" },\n ],\n }),\n }),\n },\n {\n name: \"apiKey\",\n displayName: \"API key\",\n type: o.optional({ type: o.encrypted({ type: o.string({}) }) }),\n },\n { name: \"expiresAt\", displayName: \"Expires at\", type: o.optional({ type: o.timestamp({}) }) },\n ],\n },\n {\n name: \"ExternalSessionConnection\",\n pluralDisplayName: \"External session connections\",\n displayName: \"External session connection\",\n primaryKey: \"id\",\n properties: [\n { name: \"id\", displayName: \"Id\", type: o.string({}) },\n { name: \"title\", displayName: \"Title\", type: o.string({}) },\n {\n name: \"serviceInstance\",\n displayName: \"Service instance\",\n type: o.objectReference({ objectType: \"ServiceInstance\" }),\n },\n { name: \"userId\", displayName: \"User id\", type: o.string({}) },\n {\n name: \"status\",\n displayName: \"Status\",\n type: o.string({\n constraint: o.StringConstraint.enum({\n options: [\n { value: \"active\", label: \"Active\" },\n { value: \"needs-auth\", label: \"Needs authentication\" },\n { value: \"inactive\", label: \"Inactive\" },\n ],\n }),\n }),\n },\n // A selector, not a transferable credential. The service must verify its own session.\n { name: \"sessionId\", displayName: \"Session id\", type: o.string({}) },\n { name: \"expiresAt\", displayName: \"Expires at\", type: o.optional({ type: o.timestamp({}) }) },\n ],\n },\n {\n name: \"OAuthAuthorizationAttempt\",\n pluralDisplayName: \"OAuthAuthorizationAttempts\",\n displayName: \"OAuth authorization attempt\",\n primaryKey: \"id\",\n properties: [\n { name: \"id\", displayName: \"Id\", type: o.string({}) },\n {\n name: \"application\",\n displayName: \"Application\",\n type: o.objectReference({ objectType: \"OAuthApplication\" }),\n },\n {\n name: \"principalId\",\n displayName: \"Principal id\",\n type: o.optional({ type: o.string({}) }),\n },\n {\n name: \"connectionId\",\n displayName: \"Connection id\",\n type: o.string({}),\n },\n { name: \"redirectUrl\", displayName: \"Redirect url\", type: o.string({}) },\n { name: \"returnUrl\", displayName: \"Return url\", type: o.optional({ type: o.string({}) }) },\n {\n name: \"codeVerifier\",\n displayName: \"Code verifier\",\n type: o.encrypted({ type: o.string({}) }),\n },\n { name: \"expiresAt\", displayName: \"Expires at\", type: o.timestamp({}) },\n {\n name: \"status\",\n displayName: \"Status\",\n type: o.string({\n constraint: o.StringConstraint.enum({\n options: [\n { value: \"pending\", label: \"pending\" },\n { value: \"exchanging\", label: \"exchanging\" },\n { value: \"completed\", label: \"completed\" },\n { value: \"failed\", label: \"failed\" },\n ],\n }),\n }),\n },\n ],\n },\n ],\n linkTypes: [],\n actionTypes: [\n {\n name: \"beginAuthorization\",\n displayName: \"Begin authorization\",\n logic: [],\n parameters: [\n {\n name: \"applicationId\",\n displayName: \"Application\",\n type: o.objectReference({ objectType: \"OAuthApplication\" }),\n },\n { name: \"principalId\", displayName: \"Principal\", type: o.optional({ type: o.string({}) }) },\n { name: \"redirectUrl\", displayName: \"Redirect URL\", type: o.string({}) },\n { name: \"returnUrl\", displayName: \"Return URL\", type: o.optional({ type: o.string({}) }) },\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.optional({ type: o.objectReference({ objectType: \"OAuthConnection\" }) }),\n },\n ],\n returnType: o.struct({\n fields: [\n { name: \"id\", displayName: \"Attempt\", type: o.string({}) },\n { name: \"authorizationUrl\", displayName: \"Authorization URL\", type: o.string({}) },\n ],\n }),\n },\n {\n name: \"completeAuthorization\",\n displayName: \"Complete authorization\",\n logic: [],\n parameters: [\n { name: \"callbackUrl\", displayName: \"Callback URL\", type: o.string({}) },\n { name: \"principalId\", displayName: \"Principal\", type: o.optional({ type: o.string({}) }) },\n ],\n returnType: o.struct({\n fields: [\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.objectReference({ objectType: \"OAuthConnection\" }),\n },\n ],\n }),\n },\n {\n name: \"connectClientCredentials\",\n displayName: \"Connect client credentials\",\n logic: [],\n parameters: [\n {\n name: \"applicationId\",\n displayName: \"Application\",\n type: o.objectReference({ objectType: \"OAuthApplication\" }),\n },\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.optional({ type: o.objectReference({ objectType: \"OAuthConnection\" }) }),\n },\n ],\n returnType: o.struct({\n fields: [\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.objectReference({ objectType: \"OAuthConnection\" }),\n },\n ],\n }),\n },\n {\n name: \"refreshConnection\",\n displayName: \"Refresh connection\",\n logic: [],\n parameters: [\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.objectReference({ objectType: \"OAuthConnection\" }),\n },\n ],\n returnType: o.struct({\n fields: [\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.objectReference({ objectType: \"OAuthConnection\" }),\n },\n ],\n }),\n },\n {\n name: \"disconnectConnection\",\n displayName: \"Disconnect connection\",\n logic: [],\n parameters: [\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.objectReference({ objectType: \"OAuthConnection\" }),\n },\n ],\n },\n {\n name: \"forgetConnection\",\n displayName: \"Forget connection\",\n logic: [],\n parameters: [\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.objectReference({ objectType: \"OAuthConnection\" }),\n },\n ],\n },\n {\n name: \"connectApiKey\",\n displayName: \"Connect API key\",\n logic: [],\n parameters: [\n {\n name: \"serviceInstanceId\",\n displayName: \"Service instance\",\n type: o.objectReference({ objectType: \"ServiceInstance\" }),\n },\n { name: \"apiKey\", displayName: \"API key\", type: o.string({}) },\n ],\n returnType: o.struct({\n fields: [\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.objectReference({ objectType: \"ApiKeyConnection\" }),\n },\n ],\n }),\n },\n {\n name: \"attachExternalSession\",\n displayName: \"Attach external session\",\n logic: [],\n parameters: [\n {\n name: \"serviceInstanceId\",\n displayName: \"Service instance\",\n type: o.objectReference({ objectType: \"ServiceInstance\" }),\n },\n { name: \"sessionId\", displayName: \"Session id\", type: o.string({}) },\n ],\n returnType: o.struct({\n fields: [\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.objectReference({ objectType: \"ExternalSessionConnection\" }),\n },\n ],\n }),\n },\n {\n name: \"disconnectApiKey\",\n displayName: \"Disconnect API key\",\n logic: [],\n parameters: [\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.objectReference({ objectType: \"ApiKeyConnection\" }),\n },\n ],\n },\n {\n name: \"forgetApiKey\",\n displayName: \"Forget API key\",\n logic: [],\n parameters: [\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.objectReference({ objectType: \"ApiKeyConnection\" }),\n },\n ],\n },\n {\n name: \"disconnectExternalSession\",\n displayName: \"Disconnect external session\",\n logic: [],\n parameters: [\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.objectReference({ objectType: \"ExternalSessionConnection\" }),\n },\n ],\n },\n {\n name: \"forgetExternalSession\",\n displayName: \"Forget external session\",\n logic: [],\n parameters: [\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.objectReference({ objectType: \"ExternalSessionConnection\" }),\n },\n ],\n },\n ],\n queryFunctionTypes: [],\n});\nexport type ConnectOntology = Infer<typeof connectOntology>;\nexport type ServiceInstanceRecord = ConnectOntology[\"objectTypes\"][\"ServiceInstance\"];\nexport type OAuthApplicationRecord = ConnectOntology[\"objectTypes\"][\"OAuthApplication\"];\nexport type OAuthConnectionRecord = ConnectOntology[\"objectTypes\"][\"OAuthConnection\"];\nexport type ApiKeyConnectionRecord = ConnectOntology[\"objectTypes\"][\"ApiKeyConnection\"];\nexport type ExternalSessionConnectionRecord = ConnectOntology[\"objectTypes\"][\"ExternalSessionConnection\"];\nexport type OAuthAuthorizationAttemptRecord = ConnectOntology[\"objectTypes\"][\"OAuthAuthorizationAttempt\"];\n"],"mappings":";;;;;AAKA,MAAa,kBAAkB,eAAe;CAC1C,OAAO,CAAC;CACR,aAAa;EACT;GACI,MAAM;GACN,mBAAmB;GACnB,aAAa;GACb,YAAY;GACZ,YAAY;IACR;KAAE,MAAM;KAAM,aAAa;KAAM,MAAM,EAAE,OAAO,CAAC,CAAC;IAAE;IACpD;KAAE,MAAM;KAAS,aAAa;KAAS,MAAM,EAAE,OAAO,CAAC,CAAC;IAAE;IAC1D;KAAE,MAAM;KAAW,aAAa;KAAW,MAAM,EAAE,OAAO,CAAC,CAAC;IAAE;IAC9D;KAAE,MAAM;KAAe,aAAa;KAAgB,MAAM,EAAE,OAAO,CAAC,CAAC;IAAE;GAC3E;EACJ;EACA;GACI,MAAM;GACN,mBAAmB;GACnB,aAAa;GACb,YAAY;GACZ,YAAY;IACR;KAAE,MAAM;KAAM,aAAa;KAAM,MAAM,EAAE,OAAO,CAAC,CAAC;IAAE;IACpD;KAAE,MAAM;KAAS,aAAa;KAAS,MAAM,EAAE,OAAO,CAAC,CAAC;IAAE;IAC1D;KACI,MAAM;KACN,aAAa;KACb,MAAM,EAAE,gBAAgB,EAAE,YAAY,kBAAkB,CAAC;IAC7D;IACA;KACI,MAAM;KACN,aAAa;KACb,MAAM,EAAE,OAAO,EACX,YAAY,EAAE,iBAAiB,KAAK,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ACjB,QAAQ,CACJ;IACI,MAAM;IACN,aAAa;IACb,MAAM,EAAE,gBAAgB,EAAE,YAAY,mBAAmB,CAAC;GAC9D,CACJ,EACJ,CAAC;EACL;EACA;GACI,MAAM;GACN,aAAa;GACb,OAAO,CAAC;GACR,YAAY,CACR;IACI,MAAM;IACN,aAAa;IACb,MAAM,EAAE,gBAAgB,EAAE,YAAY,kBAAkB,CAAC;GAC7D,GACA;IAAE,MAAM;IAAa,aAAa;IAAc,MAAM,EAAE,OAAO,CAAC,CAAC;GAAE,CACvE;GACA,YAAY,EAAE,OAAO,EACjB,QAAQ,CACJ;IACI,MAAM;IACN,aAAa;IACb,MAAM,EAAE,gBAAgB,EAAE,YAAY,4BAA4B,CAAC;GACvE,CACJ,EACJ,CAAC;EACL;EACA;GACI,MAAM;GACN,aAAa;GACb,OAAO,CAAC;GACR,YAAY,CACR;IACI,MAAM;IACN,aAAa;IACb,MAAM,EAAE,gBAAgB,EAAE,YAAY,mBAAmB,CAAC;GAC9D,CACJ;EACJ;EACA;GACI,MAAM;GACN,aAAa;GACb,OAAO,CAAC;GACR,YAAY,CACR;IACI,MAAM;IACN,aAAa;IACb,MAAM,EAAE,gBAAgB,EAAE,YAAY,mBAAmB,CAAC;GAC9D,CACJ;EACJ;EACA;GACI,MAAM;GACN,aAAa;GACb,OAAO,CAAC;GACR,YAAY,CACR;IACI,MAAM;IACN,aAAa;IACb,MAAM,EAAE,gBAAgB,EAAE,YAAY,4BAA4B,CAAC;GACvE,CACJ;EACJ;EACA;GACI,MAAM;GACN,aAAa;GACb,OAAO,CAAC;GACR,YAAY,CACR;IACI,MAAM;IACN,aAAa;IACb,MAAM,EAAE,gBAAgB,EAAE,YAAY,4BAA4B,CAAC;GACvE,CACJ;EACJ;CACJ;CACA,oBAAoB,CAAC;AACzB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/spec/index.ts"],"sourcesContent":["import { defineOntology, o, type Infer } from \"@party-stack/ontology-spec\";\n\n/** Portable definitions. Applications may add properties/links before compiling them.\n * Connection and attempt instances are private to the credential authority.\n */\nexport const connectOntology = defineOntology({\n types: [],\n objectTypes: [\n {\n name: \"ServiceInstance\",\n pluralDisplayName: \"Service instances\",\n displayName: \"Service instance\",\n primaryKey: \"id\",\n properties: [\n { name: \"id\", displayName: \"Id\", type: o.string({}) },\n { name: \"title\", displayName: \"Title\", type: o.string({}) },\n { name: \"service\", displayName: \"Service\", type: o.string({}) },\n { name: \"instanceUrl\", displayName: \"Instance url\", type: o.string({}) },\n ],\n },\n {\n name: \"OAuthApplication\",\n pluralDisplayName: \"OAuthApplications\",\n displayName: \"OAuth application\",\n primaryKey: \"id\",\n properties: [\n { name: \"id\", displayName: \"Id\", type: o.string({}) },\n { name: \"title\", displayName: \"Title\", type: o.string({}) },\n {\n name: \"serviceInstance\",\n displayName: \"Service instance\",\n type: o.objectReference({ objectType: \"ServiceInstance\" }),\n },\n {\n name: \"flow\",\n displayName: \"Flow\",\n type: o.string({\n constraint: o.StringConstraint.enum({\n options: [\n { value: \"authorization-code\", label: \"authorization-code\" },\n { value: \"client-credentials\", label: \"client-credentials\" },\n ],\n }),\n }),\n },\n { name: \"clientId\", displayName: \"Client id\", type: o.string({}) },\n {\n name: \"scopes\",\n displayName: \"Requested scopes\",\n type: o.optional({ type: o.list({ elementType: o.string({}) }) }),\n },\n {\n name: \"redirectUrl\",\n displayName: \"Redirect URL\",\n type: o.optional({ type: o.string({}) }),\n },\n {\n name: \"clientSecret\",\n displayName: \"Client secret\",\n type: o.optional({ type: o.encrypted({ type: o.string({}) }) }),\n },\n {\n name: \"serviceAppId\",\n displayName: \"Service app id\",\n type: o.optional({ type: o.string({}) }),\n },\n {\n name: \"connection\",\n displayName: \"Connection\",\n type: o.optional({ type: o.objectReference({ objectType: \"OAuthConnection\" }) }),\n },\n ],\n },\n {\n name: \"OAuthConnection\",\n pluralDisplayName: \"OAuthConnections\",\n displayName: \"OAuth connection\",\n primaryKey: \"id\",\n properties: [\n { name: \"id\", displayName: \"Id\", type: o.string({}) },\n { name: \"title\", displayName: \"Title\", type: o.string({}) },\n {\n name: \"application\",\n displayName: \"Application\",\n type: o.objectReference({ objectType: \"OAuthApplication\" }),\n },\n {\n name: \"userId\",\n displayName: \"User id\",\n type: o.optional({ type: o.string({}) }),\n },\n {\n name: \"status\",\n displayName: \"Status\",\n type: o.string({\n constraint: o.StringConstraint.enum({\n options: [\n { value: \"active\", label: \"active\" },\n { value: \"needs-auth\", label: \"needs-auth\" },\n { value: \"inactive\", label: \"inactive\" },\n ],\n }),\n }),\n },\n {\n name: \"statusReason\",\n displayName: \"Status reason\",\n // Never credentials or provider response bodies.\n description: \"Why the connection needs a sign-in, when known.\",\n type: o.optional({ type: o.string({}) }),\n },\n {\n name: \"accessToken\",\n displayName: \"Access token\",\n type: o.optional({ type: o.encrypted({ type: o.string({}) }) }),\n },\n {\n name: \"accessTokenExpiresAt\",\n displayName: \"Access token expires at\",\n type: o.optional({ type: o.timestamp({}) }),\n },\n {\n name: \"refreshToken\",\n displayName: \"Refresh token\",\n type: o.optional({ type: o.encrypted({ type: o.string({}) }) }),\n },\n {\n name: \"refreshTokenExpiresAt\",\n displayName: \"Refresh token expires at\",\n type: o.optional({ type: o.timestamp({}) }),\n },\n {\n name: \"grantedScopes\",\n displayName: \"Granted scopes\",\n type: o.optional({ type: o.string({}) }),\n },\n {\n name: \"operationId\",\n displayName: \"Operation id\",\n type: o.optional({ type: o.string({}) }),\n },\n {\n name: \"operationExpiresAt\",\n displayName: \"Operation expires at\",\n type: o.optional({ type: o.timestamp({}) }),\n },\n ],\n },\n {\n name: \"ApiKeyConnection\",\n pluralDisplayName: \"API key connections\",\n displayName: \"API key connection\",\n primaryKey: \"id\",\n properties: [\n { name: \"id\", displayName: \"Id\", type: o.string({}) },\n { name: \"title\", displayName: \"Title\", type: o.string({}) },\n {\n name: \"serviceInstance\",\n displayName: \"Service instance\",\n type: o.objectReference({ objectType: \"ServiceInstance\" }),\n },\n { name: \"userId\", displayName: \"User id\", type: o.string({}) },\n {\n name: \"status\",\n displayName: \"Status\",\n type: o.string({\n constraint: o.StringConstraint.enum({\n options: [\n { value: \"active\", label: \"Active\" },\n { value: \"needs-auth\", label: \"Needs authentication\" },\n { value: \"inactive\", label: \"Inactive\" },\n ],\n }),\n }),\n },\n {\n name: \"statusReason\",\n displayName: \"Status reason\",\n // Never credentials or provider response bodies.\n description: \"Why the connection needs a sign-in, when known.\",\n type: o.optional({ type: o.string({}) }),\n },\n {\n name: \"apiKey\",\n displayName: \"API key\",\n type: o.optional({ type: o.encrypted({ type: o.string({}) }) }),\n },\n { name: \"expiresAt\", displayName: \"Expires at\", type: o.optional({ type: o.timestamp({}) }) },\n ],\n },\n {\n name: \"ExternalSessionConnection\",\n pluralDisplayName: \"External session connections\",\n displayName: \"External session connection\",\n primaryKey: \"id\",\n properties: [\n { name: \"id\", displayName: \"Id\", type: o.string({}) },\n { name: \"title\", displayName: \"Title\", type: o.string({}) },\n {\n name: \"serviceInstance\",\n displayName: \"Service instance\",\n type: o.objectReference({ objectType: \"ServiceInstance\" }),\n },\n { name: \"userId\", displayName: \"User id\", type: o.string({}) },\n {\n name: \"status\",\n displayName: \"Status\",\n type: o.string({\n constraint: o.StringConstraint.enum({\n options: [\n { value: \"active\", label: \"Active\" },\n { value: \"needs-auth\", label: \"Needs authentication\" },\n { value: \"inactive\", label: \"Inactive\" },\n ],\n }),\n }),\n },\n {\n name: \"statusReason\",\n displayName: \"Status reason\",\n // Never credentials or provider response bodies.\n description: \"Why the connection needs a sign-in, when known.\",\n type: o.optional({ type: o.string({}) }),\n },\n // A selector, not a transferable credential. The service must verify its own session.\n { name: \"sessionId\", displayName: \"Session id\", type: o.string({}) },\n { name: \"expiresAt\", displayName: \"Expires at\", type: o.optional({ type: o.timestamp({}) }) },\n ],\n },\n {\n name: \"OAuthAuthorizationAttempt\",\n pluralDisplayName: \"OAuthAuthorizationAttempts\",\n displayName: \"OAuth authorization attempt\",\n primaryKey: \"id\",\n properties: [\n { name: \"id\", displayName: \"Id\", type: o.string({}) },\n {\n name: \"application\",\n displayName: \"Application\",\n type: o.objectReference({ objectType: \"OAuthApplication\" }),\n },\n {\n name: \"principalId\",\n displayName: \"Principal id\",\n type: o.optional({ type: o.string({}) }),\n },\n {\n name: \"connectionId\",\n displayName: \"Connection id\",\n type: o.string({}),\n },\n { name: \"redirectUrl\", displayName: \"Redirect url\", type: o.string({}) },\n { name: \"returnUrl\", displayName: \"Return url\", type: o.optional({ type: o.string({}) }) },\n {\n name: \"codeVerifier\",\n displayName: \"Code verifier\",\n type: o.encrypted({ type: o.string({}) }),\n },\n { name: \"expiresAt\", displayName: \"Expires at\", type: o.timestamp({}) },\n {\n name: \"status\",\n displayName: \"Status\",\n type: o.string({\n constraint: o.StringConstraint.enum({\n options: [\n { value: \"pending\", label: \"pending\" },\n { value: \"exchanging\", label: \"exchanging\" },\n { value: \"completed\", label: \"completed\" },\n { value: \"failed\", label: \"failed\" },\n ],\n }),\n }),\n },\n ],\n },\n ],\n linkTypes: [],\n actionTypes: [\n {\n name: \"beginAuthorization\",\n displayName: \"Begin authorization\",\n logic: [],\n parameters: [\n {\n name: \"applicationId\",\n displayName: \"Application\",\n type: o.objectReference({ objectType: \"OAuthApplication\" }),\n },\n { name: \"principalId\", displayName: \"Principal\", type: o.optional({ type: o.string({}) }) },\n { name: \"redirectUrl\", displayName: \"Redirect URL\", type: o.string({}) },\n { name: \"returnUrl\", displayName: \"Return URL\", type: o.optional({ type: o.string({}) }) },\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.optional({ type: o.objectReference({ objectType: \"OAuthConnection\" }) }),\n },\n ],\n returnType: o.struct({\n fields: [\n { name: \"id\", displayName: \"Attempt\", type: o.string({}) },\n { name: \"authorizationUrl\", displayName: \"Authorization URL\", type: o.string({}) },\n ],\n }),\n },\n {\n name: \"completeAuthorization\",\n displayName: \"Complete authorization\",\n logic: [],\n parameters: [\n { name: \"callbackUrl\", displayName: \"Callback URL\", type: o.string({}) },\n { name: \"principalId\", displayName: \"Principal\", type: o.optional({ type: o.string({}) }) },\n ],\n returnType: o.struct({\n fields: [\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.objectReference({ objectType: \"OAuthConnection\" }),\n },\n ],\n }),\n },\n {\n name: \"connectClientCredentials\",\n displayName: \"Connect client credentials\",\n logic: [],\n parameters: [\n {\n name: \"applicationId\",\n displayName: \"Application\",\n type: o.objectReference({ objectType: \"OAuthApplication\" }),\n },\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.optional({ type: o.objectReference({ objectType: \"OAuthConnection\" }) }),\n },\n ],\n returnType: o.struct({\n fields: [\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.objectReference({ objectType: \"OAuthConnection\" }),\n },\n ],\n }),\n },\n {\n name: \"refreshConnection\",\n displayName: \"Refresh connection\",\n logic: [],\n parameters: [\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.objectReference({ objectType: \"OAuthConnection\" }),\n },\n ],\n returnType: o.struct({\n fields: [\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.objectReference({ objectType: \"OAuthConnection\" }),\n },\n ],\n }),\n },\n {\n name: \"disconnectConnection\",\n displayName: \"Disconnect connection\",\n logic: [],\n parameters: [\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.objectReference({ objectType: \"OAuthConnection\" }),\n },\n ],\n },\n {\n name: \"forgetConnection\",\n displayName: \"Forget connection\",\n logic: [],\n parameters: [\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.objectReference({ objectType: \"OAuthConnection\" }),\n },\n ],\n },\n {\n name: \"connectApiKey\",\n displayName: \"Connect API key\",\n logic: [],\n parameters: [\n {\n name: \"serviceInstanceId\",\n displayName: \"Service instance\",\n type: o.objectReference({ objectType: \"ServiceInstance\" }),\n },\n { name: \"apiKey\", displayName: \"API key\", type: o.string({}) },\n ],\n returnType: o.struct({\n fields: [\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.objectReference({ objectType: \"ApiKeyConnection\" }),\n },\n ],\n }),\n },\n {\n name: \"attachExternalSession\",\n displayName: \"Attach external session\",\n logic: [],\n parameters: [\n {\n name: \"serviceInstanceId\",\n displayName: \"Service instance\",\n type: o.objectReference({ objectType: \"ServiceInstance\" }),\n },\n { name: \"sessionId\", displayName: \"Session id\", type: o.string({}) },\n ],\n returnType: o.struct({\n fields: [\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.objectReference({ objectType: \"ExternalSessionConnection\" }),\n },\n ],\n }),\n },\n {\n name: \"disconnectApiKey\",\n displayName: \"Disconnect API key\",\n logic: [],\n parameters: [\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.objectReference({ objectType: \"ApiKeyConnection\" }),\n },\n ],\n },\n {\n name: \"forgetApiKey\",\n displayName: \"Forget API key\",\n logic: [],\n parameters: [\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.objectReference({ objectType: \"ApiKeyConnection\" }),\n },\n ],\n },\n {\n name: \"disconnectExternalSession\",\n displayName: \"Disconnect external session\",\n logic: [],\n parameters: [\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.objectReference({ objectType: \"ExternalSessionConnection\" }),\n },\n ],\n },\n {\n name: \"forgetExternalSession\",\n displayName: \"Forget external session\",\n logic: [],\n parameters: [\n {\n name: \"connectionId\",\n displayName: \"Connection\",\n type: o.objectReference({ objectType: \"ExternalSessionConnection\" }),\n },\n ],\n },\n ],\n queryFunctionTypes: [],\n});\nexport type ConnectOntology = Infer<typeof connectOntology>;\nexport type ServiceInstanceRecord = ConnectOntology[\"objectTypes\"][\"ServiceInstance\"];\nexport type OAuthApplicationRecord = ConnectOntology[\"objectTypes\"][\"OAuthApplication\"];\nexport type OAuthConnectionRecord = ConnectOntology[\"objectTypes\"][\"OAuthConnection\"];\nexport type ApiKeyConnectionRecord = ConnectOntology[\"objectTypes\"][\"ApiKeyConnection\"];\nexport type ExternalSessionConnectionRecord = ConnectOntology[\"objectTypes\"][\"ExternalSessionConnection\"];\nexport type OAuthAuthorizationAttemptRecord = ConnectOntology[\"objectTypes\"][\"OAuthAuthorizationAttempt\"];\n"],"mappings":";;;;;AAKA,MAAa,kBAAkB,eAAe;CAC1C,OAAO,CAAC;CACR,aAAa;EACT;GACI,MAAM;GACN,mBAAmB;GACnB,aAAa;GACb,YAAY;GACZ,YAAY;IACR;KAAE,MAAM;KAAM,aAAa;KAAM,MAAM,EAAE,OAAO,CAAC,CAAC;IAAE;IACpD;KAAE,MAAM;KAAS,aAAa;KAAS,MAAM,EAAE,OAAO,CAAC,CAAC;IAAE;IAC1D;KAAE,MAAM;KAAW,aAAa;KAAW,MAAM,EAAE,OAAO,CAAC,CAAC;IAAE;IAC9D;KAAE,MAAM;KAAe,aAAa;KAAgB,MAAM,EAAE,OAAO,CAAC,CAAC;IAAE;GAC3E;EACJ;EACA;GACI,MAAM;GACN,mBAAmB;GACnB,aAAa;GACb,YAAY;GACZ,YAAY;IACR;KAAE,MAAM;KAAM,aAAa;KAAM,MAAM,EAAE,OAAO,CAAC,CAAC;IAAE;IACpD;KAAE,MAAM;KAAS,aAAa;KAAS,MAAM,EAAE,OAAO,CAAC,CAAC;IAAE;IAC1D;KACI,MAAM;KACN,aAAa;KACb,MAAM,EAAE,gBAAgB,EAAE,YAAY,kBAAkB,CAAC;IAC7D;IACA;KACI,MAAM;KACN,aAAa;KACb,MAAM,EAAE,OAAO,EACX,YAAY,EAAE,iBAAiB,KAAK,EAChC,SAAS,CACL;MAAE,OAAO;MAAsB,OAAO;KAAqB,GAC3D;MAAE,OAAO;MAAsB,OAAO;KAAqB,CAC/D,EACJ,CAAC,EACL,CAAC;IACL;IACA;KAAE,MAAM;KAAY,aAAa;KAAa,MAAM,EAAE,OAAO,CAAC,CAAC;IAAE;IACjE;KACI,MAAM;KACN,aAAa;KACb,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE,aAAa,EAAE,OAAO,CA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
{
|
|
2
2
|
"name": "@party-stack/connect",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.3",
|
|
4
4
|
"files": [
|
|
5
5
|
"lib"
|
|
6
6
|
],
|
|
@@ -23,10 +23,10 @@
|
|
|
23
23
|
"effect": "^4.0.5",
|
|
24
24
|
"oauth4webapi": "^3.8.7",
|
|
25
25
|
"temporal-polyfill": "^0.3.0",
|
|
26
|
-
"@party-stack/ontology-backend": "0.
|
|
27
|
-
"@party-stack/ontology-spec": "0.5.
|
|
28
|
-
"@party-stack/ontology-storage": "0.4.
|
|
29
|
-
"@party-stack/runtime": "0.
|
|
26
|
+
"@party-stack/ontology-backend": "0.7.0",
|
|
27
|
+
"@party-stack/ontology-spec": "0.5.1",
|
|
28
|
+
"@party-stack/ontology-storage": "0.4.1",
|
|
29
|
+
"@party-stack/runtime": "0.7.0"
|
|
30
30
|
},
|
|
31
31
|
"devDependencies": {
|
|
32
32
|
"typescript": "~7.0.2",
|