Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SecretProviderDialog.logic.ts

131 lines4.4 KB

1import {
2 SecretProviderId,
3 SecretProviderKind,
4 SecretProviderLabel,
5 type SecretProviderConfig,
6} from "@t3tools/contracts";
7import {
8 OnePasswordSecretProviderConfig,
9 type OnePasswordAccount,
10} from "@t3tools/secret-provider-onepassword/shared/definition";
11import * as Option from "effect/Option";
12import * as Result from "effect/Result";
13import * as Schema from "effect/Schema";
14import { msg } from "gt-react";
15​
16import { m, type MessageResolver } from "../../i18n/messages";
17​
18const decodeSecretProviderId = Schema.decodeOption(SecretProviderId);
19const decodeOnePasswordConfig = Schema.decodeUnknownOption(OnePasswordSecretProviderConfig);
20​
21export type ClassifiedSecretProvider =
22 | { readonly kind: "one_password"; readonly account: OnePasswordAccount }
23 | { readonly kind: "unsupported" };
24​
25/** Unknown kinds and configs that no longer decode are shown read-only; removal stays available. */
26export function classifySecretProvider(provider: SecretProviderConfig): ClassifiedSecretProvider {
27 if (provider.kind !== "one_password") return { kind: "unsupported" };
28 const decoded = decodeOnePasswordConfig(provider.config);
29 return decoded._tag === "Some"
30 ? { kind: "one_password", account: decoded.value.account }
31 : { kind: "unsupported" };
33​
34/** Stable and readable in settings.json, so re-adding a provider under the same name restores its variables. */
35function secretProviderIdFromName(name: string): SecretProviderId | null {
36 const slug = name
37 .toLowerCase()
38 .replace(/[^a-z0-9]+/g, "-")
39 .replace(/^-|-$/g, "")
40 .slice(0, 64)
41 .replace(/-$/, "");
42 return Option.getOrNull(decodeSecretProviderId(slug));
44​
45/** Names with no Latin letter or digit (Cyrillic, CJK) have no slug, so they take the first free generic id. */
46function fallbackSecretProviderId(existingIds: ReadonlySet<string>): SecretProviderId {
47 for (let n = 1; ; n += 1) {
48 const id = SecretProviderId.make(n === 1 ? "one-password" : `one-password-${n}`);
49 if (!existingIds.has(id)) return id;
50 }
52​
53export interface SecretProviderDraft {
54 readonly name: string;
55 readonly account: string;
57​
58export function draftFromSecretProvider(provider: SecretProviderConfig): SecretProviderDraft {
59 const classified = classifySecretProvider(provider);
60 return {
61 name: provider.label,
62 account: classified.kind === "one_password" ? classified.account : "",
63 };
65​
66export type SecretProviderTarget =
67 | { readonly mode: "add" }
68 | { readonly mode: "edit"; readonly id: SecretProviderId };
69​
70export type SecretProviderDraftIssues = {
71 readonly [Field in keyof SecretProviderDraft]?: string;
72};
73​
74function decodeField<S extends Schema.ConstraintDecoder<unknown>>(
75 schema: S,
76 value: string,
77 emptyMessage: string,
78): Result.Result<S["Type"], string> {
79 const trimmed = value.trim();
80 if (trimmed.length === 0) return Result.fail(emptyMessage);
81 return Result.mapError(Schema.decodeResult(schema)(trimmed), (error) => error.message);
83​
84/** The settings entry a draft adds or replaces, or every field that blocks it, one message each. */
85export function secretProviderFromDraft(
86 draft: SecretProviderDraft,
87 existingIds: ReadonlySet<string>,
88 target: SecretProviderTarget,
89 resolve: MessageResolver = m,
90): Result.Result<
91 { readonly id: SecretProviderId; readonly config: SecretProviderConfig },
92 SecretProviderDraftIssues
93> {
94 const label = decodeField(SecretProviderLabel, draft.name, resolve(msg("Enter a name.")));
95 const account = decodeField(
96 OnePasswordSecretProviderConfig.fields.account,
97 draft.account,
98 resolve(msg("Enter the 1Password account.")),
99 );
100​
101 let id: SecretProviderId | null = null;
102 let nameIssue: string | undefined;
103 if (Result.isFailure(label)) {
104 nameIssue = label.failure;
105 } else if (target.mode === "edit") {
106 id = target.id;
107 } else {
108 id = secretProviderIdFromName(label.success) ?? fallbackSecretProviderId(existingIds);
109 if (existingIds.has(id)) nameIssue = resolve(msg("A secret provider with this name exists."));
110 }
111​
112 if (
113 id === null ||
114 nameIssue !== undefined ||
115 Result.isFailure(label) ||
116 Result.isFailure(account)
117 ) {
118 return Result.fail({
119 ...(nameIssue === undefined ? {} : { name: nameIssue }),
120 ...(Result.isFailure(account) ? { account: account.failure } : {}),
121 });
122 }
123 return Result.succeed({
124 id,
125 config: {
126 kind: SecretProviderKind.make("one_password"),
127 label: label.success,
128 config: { account: account.success },
129 },
130 });