summaryrefslogtreecommitdiff
path: root/worker/secret.ts
blob: 34056c2896720d8372b67f4b631998c88ad3898b (plain)
1
2
3
4
5
6
7
8
9
10
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import {
    Either,
    getRequiredEnvVars,
    getStdout,
    getStdoutMany,
    type IEither,
    type ITraceable,
    type LogMetricTraceSupplier,
    Metric,
    TraceUtil,
} from '@emprespresso/pengueno';
import { randomUUID } from 'node:crypto';
import { mkdirSync } from 'node:fs';
import path from 'node:path';

// -- <ISecret> --
export interface SecretItem {
    name: string;
}

export interface LoginItem extends SecretItem {
    login: {
        username: string;
        password: string;
    };
}

export interface SecureNote extends SecretItem {
    notes: string;
}

export interface IVault<TClient, TKey, TItemId> {
    unlock: (client: TClient) => Promise<IEither<Error, TKey>>;
    lock: (client: TClient, key: TKey) => Promise<IEither<Error, TKey>>;

    fetchSecret: <T extends SecretItem>(client: TClient, key: TKey, item: TItemId) => Promise<IEither<Error, T>>;
}
// -- </ISecret> --

// -- <Vault> --
type TClient = ITraceable<unknown, LogMetricTraceSupplier>;
export type BitwardenKey = {
    BW_SESSION: string;
    BITWARDENCLI_APPDATA_DIR: string;
};
type TItemId = string;
export class Bitwarden implements IVault<TClient, BitwardenKey, TItemId> {
    constructor(private readonly config: BitwardenConfig) {}

    public unlock(client: TClient) {
        return client
            .move(this.config)
            .flatMap(TraceUtil.withMetricTrace(Bitwarden.loginMetric))
            .map((tConfig) =>
                Either.fromFailable<
                    Error,
                    { config: BitwardenConfig; key: Pick<BitwardenKey, 'BITWARDENCLI_APPDATA_DIR'> }
                >(() => {
                    const sessionPath = path.join(this.config.sessionBaseDirectory, randomUUID());
                    mkdirSync(sessionPath, { recursive: true });
                    return { config: tConfig.get(), key: { BITWARDENCLI_APPDATA_DIR: sessionPath } };
                }),
            )
            .map((tEitherConfig) =>
                tEitherConfig
                    .get()
                    .flatMapAsync(({ config: { server }, key }) =>
                        getStdoutMany(
                            tEitherConfig.move([
                                `bw config server ${server}`,
                                `bw login --apikey --quiet`,
                                `bw unlock --passwordenv BW_PASSWORD --raw`,
                            ]),
                            { env: key },
                        ).then((res) => res.mapRight((out) => ({ ...key, BW_SESSION: out.at(-1)! }))),
                    ),
            )
            .peek(TraceUtil.promiseify(TraceUtil.traceResultingEither(Bitwarden.loginMetric)))
            .get();
    }

    public fetchSecret<T extends SecretItem>(
        client: TClient,
        key: BitwardenKey,
        item: string,
    ): Promise<IEither<Error, T>> {
        return client
            .move(key)
            .flatMap(TraceUtil.withMetricTrace(Bitwarden.fetchSecretMetric))
            .peek((tSession) => tSession.trace.trace(`looking for your secret ${item} (⑅˘꒳˘)`))
            .flatMap((tSession) =>
                tSession.move(`bw list items --search ${item}`).map((listCmd) => getStdout(listCmd, { env: key })),
            )
            .map(
                TraceUtil.promiseify((tEitherItemsJson) =>
                    tEitherItemsJson
                        .get()
                        .flatMap(
                            (itemsJson): IEither<Error, Array<T>> => Either.fromFailable(() => JSON.parse(itemsJson)),
                        )
                        .flatMap((itemsList): IEither<Error, T> => {
                            const secret = itemsList.find(({ name }) => name === item);
                            if (!secret) {
                                return Either.left(new Error(`couldn't find the item ${item} (。•́︿•̀。)`));
                            }
                            return Either.right(secret);
                        }),
                ),
            )
            .flatMapAsync(TraceUtil.promiseify(TraceUtil.traceResultingEither(Bitwarden.fetchSecretMetric)))
            .get();
    }

    public lock(client: TClient, key: BitwardenKey) {
        return client
            .move(key)
            .flatMap(TraceUtil.withMetricTrace(Bitwarden.lockVaultMetric))
            .peek((tSession) => tSession.trace.trace(`taking care of locking the vault :3`))
            .flatMap((tSession) =>
                tSession.move('bw lock && bw logout').map((lockCmd) => getStdout(lockCmd, { env: key })),
            )
            .peek(TraceUtil.promiseify(TraceUtil.traceResultingEither(Bitwarden.lockVaultMetric)))
            .peek(
                TraceUtil.promiseify((tEitherWithLocked) =>
                    tEitherWithLocked
                        .get()
                        .mapRight(() => tEitherWithLocked.trace.trace('all locked up and secure now~ (。•̀ᴗ-)✧')),
                ),
            )
            .map(TraceUtil.promiseify((e) => e.get().mapRight(() => key)))
            .get();
    }

    public static getConfigFromEnvironment(sessionBaseDirectory = '/tmp/secret'): IEither<Error, BitwardenConfig> {
        return getRequiredEnvVars(['BW_SERVER', 'BW_CLIENTSECRET', 'BW_CLIENTID', 'BW_PASSWORD']).mapRight(
            ({ BW_SERVER, BW_CLIENTSECRET, BW_CLIENTID }) => ({
                sessionBaseDirectory,
                clientId: BW_CLIENTID,
                secret: BW_CLIENTSECRET,
                server: BW_SERVER,
            }),
        );
    }

    private static loginMetric = Metric.fromName('Bitwarden.login').asResult();
    private static unlockVaultMetric = Metric.fromName('Bitwarden.unlockVault').asResult();
    private static fetchSecretMetric = Metric.fromName('Bitwarden.fetchSecret').asResult();
    private static lockVaultMetric = Metric.fromName('Bitwarden.lock').asResult();
}

export interface BitwardenConfig {
    sessionBaseDirectory: string;
    server: string;
    secret: string;
    clientId: string;
}
// -- </Vault> --