Open History to see the last commit
1import type { SdkCredentialStore } from "@cursor/sdk";
2import { ProviderSetupError, type ProviderInstanceId } from "@t3tools/contracts";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Option from "effect/Option";
6import * as Schema from "effect/Schema";
7
8import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
9
10const Credentials = Schema.fromJsonString(
11 Schema.Struct({
12 version: Schema.Literal(1),
13 backendUrl: Schema.String,
14 apiKey: Schema.String,
15 createdAtMs: Schema.Finite,
16 apiKeyExpiresAtMs: Schema.optionalKey(Schema.Finite),
17 email: Schema.optionalKey(Schema.String),
18 }),
19);
20
21const decodeCredentials = Schema.decodeUnknownEffect(Credentials);
22const encodeCredentials = Schema.encodeEffect(Credentials);
23
24export const makeCursorCredentialStore = Effect.fn("makeCursorCredentialStore")(function* (
25 instanceId: ProviderInstanceId,
26 legacyFile?: string,
27) {
28 const credentials = yield* (yield* ProviderHost.ProviderHost).credentials("cursor", instanceId);
29 if (legacyFile !== undefined) {
30 const fileSystem = yield* FileSystem.FileSystem;
31 yield* Effect.gen(function* () {
32 const legacy = yield* fileSystem.readFileString(legacyFile).pipe(Effect.option);
33 if (Option.isNone(legacy)) return;
34 const stored = yield* credentials.get;
35 const storedIsValid =
36 Option.isSome(stored) &&
37 Option.isSome(
38 yield* decodeCredentials(new TextDecoder().decode(stored.value)).pipe(Effect.option),
39 );
40 if (
41 !storedIsValid &&
42 Option.isSome(yield* decodeCredentials(legacy.value).pipe(Effect.option))
43 ) {
44 yield* credentials.set(new TextEncoder().encode(legacy.value));
45 }
46 yield* fileSystem.remove(legacyFile);
47 }).pipe(
48 Effect.catch((error) =>
49 Effect.logWarning("Could not migrate legacy Cursor credentials", error),
50 ),
51 );
52 }
53 const store: SdkCredentialStore = {
54 load: () =>
55 Effect.runPromise(
56 credentials.get.pipe(
57 Effect.flatMap(
58 Option.match({
59 onNone: () => Effect.succeed(undefined),
60 onSome: (bytes) =>
61 decodeCredentials(new TextDecoder().decode(bytes)).pipe(
62 Effect.orElseSucceed(() => undefined),
63 ),
64 }),
65 ),
66 ),
67 ),
68 save: (value) =>
69 Effect.runPromise(
70 encodeCredentials(value).pipe(
71 Effect.mapError(
72 () =>
73 new ProviderSetupError({
74 instanceId,
75 operation: "credentials",
76 detail: "Cursor returned an unsupported credential format.",
77 }),
78 ),
79 Effect.flatMap((encoded) => credentials.set(new TextEncoder().encode(encoded))),
80 ),
81 ),
82 clear: () => Effect.runPromise(credentials.remove),
83 };
84 return { store, binding: credentials.binding };
85});