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
|
import { TRPCError } from "@trpc/server";
import { and, eq } from "drizzle-orm";
import { z } from "zod";
import { apiKeys } from "@hoarder/db/schema";
import serverConfig from "@hoarder/shared/config";
import {
authenticateApiKey,
generateApiKey,
logAuthenticationError,
validatePassword,
} from "../auth";
import { authedProcedure, publicProcedure, router } from "../index";
const zApiKeySchema = z.object({
id: z.string(),
name: z.string(),
key: z.string(),
createdAt: z.date(),
});
export const apiKeysAppRouter = router({
create: authedProcedure
.input(
z.object({
name: z.string(),
}),
)
.output(zApiKeySchema)
.mutation(async ({ input, ctx }) => {
return await generateApiKey(input.name, ctx.user.id);
}),
revoke: authedProcedure
.input(
z.object({
id: z.string(),
}),
)
.mutation(async ({ input, ctx }) => {
await ctx.db
.delete(apiKeys)
.where(and(eq(apiKeys.id, input.id), eq(apiKeys.userId, ctx.user.id)));
}),
list: authedProcedure
.output(
z.object({
keys: z.array(
z.object({
id: z.string(),
name: z.string(),
createdAt: z.date(),
keyId: z.string(),
}),
),
}),
)
.query(async ({ ctx }) => {
const resp = await ctx.db.query.apiKeys.findMany({
where: eq(apiKeys.userId, ctx.user.id),
columns: {
id: true,
name: true,
createdAt: true,
keyId: true,
},
});
return { keys: resp };
}),
// Exchange the username and password with an API key.
// Homemade oAuth. This is used by the extension.
exchange: publicProcedure
.input(
z.object({
keyName: z.string(),
email: z.string(),
password: z.string(),
}),
)
.output(zApiKeySchema)
.mutation(async ({ input, ctx }) => {
let user;
// Special handling as otherwise the extension would show "username or password is wrong"
if (serverConfig.auth.disablePasswordAuth) {
throw new TRPCError({
message: "Password authentication is currently disabled",
code: "FORBIDDEN",
});
}
try {
user = await validatePassword(input.email, input.password);
} catch (e) {
const error = e as Error;
logAuthenticationError(input.email, error.message, ctx.req.ip);
throw new TRPCError({ code: "UNAUTHORIZED" });
}
return await generateApiKey(input.keyName, user.id);
}),
validate: publicProcedure
.input(z.object({ apiKey: z.string() }))
.output(z.object({ success: z.boolean() }))
.mutation(async ({ input, ctx }) => {
try {
await authenticateApiKey(input.apiKey); // Throws if the key is invalid
return {
success: true,
};
} catch (e) {
const error = e as Error;
logAuthenticationError("<unknown>", error.message, ctx.req.ip);
throw e;
}
}),
});
|