@powerhousedao/reactor-api 1.21.2 → 1.22.0

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.
Files changed (134) hide show
  1. package/dist/index.d.ts +8 -503
  2. package/dist/index.d.ts.map +1 -0
  3. package/dist/index.js +7 -27020
  4. package/dist/src/processors/analytics-processor.d.ts +9 -0
  5. package/dist/src/processors/analytics-processor.d.ts.map +1 -0
  6. package/dist/src/processors/analytics-processor.js +9 -0
  7. package/dist/src/processors/index.d.ts +5 -0
  8. package/dist/src/processors/index.d.ts.map +1 -0
  9. package/dist/src/processors/index.js +4 -0
  10. package/dist/src/processors/manager.d.ts +14 -0
  11. package/dist/src/processors/manager.d.ts.map +1 -0
  12. package/dist/src/processors/manager.js +40 -0
  13. package/dist/src/processors/operational-processor.d.ts +8 -0
  14. package/dist/src/processors/operational-processor.d.ts.map +1 -0
  15. package/dist/src/processors/operational-processor.js +12 -0
  16. package/dist/src/processors/processor.d.ts +20 -0
  17. package/dist/src/processors/processor.d.ts.map +1 -0
  18. package/dist/src/processors/processor.js +45 -0
  19. package/dist/src/server.d.ts +18 -0
  20. package/dist/src/server.d.ts.map +1 -0
  21. package/dist/src/server.js +51 -0
  22. package/dist/src/subgraphs/analytics/index.d.ts +16 -0
  23. package/dist/src/subgraphs/analytics/index.d.ts.map +1 -0
  24. package/dist/src/subgraphs/analytics/index.js +85 -0
  25. package/dist/src/subgraphs/auth/env/getters.d.ts +3 -0
  26. package/dist/src/subgraphs/auth/env/getters.d.ts.map +1 -0
  27. package/dist/src/subgraphs/auth/env/getters.js +26 -0
  28. package/dist/src/subgraphs/auth/env/index.d.ts +8 -0
  29. package/dist/src/subgraphs/auth/env/index.d.ts.map +1 -0
  30. package/{src/subgraphs/auth/env/index.ts → dist/src/subgraphs/auth/env/index.js} +4 -6
  31. package/dist/src/subgraphs/auth/index.d.ts +11 -0
  32. package/dist/src/subgraphs/auth/index.d.ts.map +1 -0
  33. package/dist/src/subgraphs/auth/index.js +259 -0
  34. package/dist/src/subgraphs/auth/types.d.ts +35 -0
  35. package/dist/src/subgraphs/auth/types.d.ts.map +1 -0
  36. package/dist/src/subgraphs/auth/types.js +1 -0
  37. package/dist/src/subgraphs/auth/utils/helpers.d.ts +12 -0
  38. package/dist/src/subgraphs/auth/utils/helpers.d.ts.map +1 -0
  39. package/dist/src/subgraphs/auth/utils/helpers.js +100 -0
  40. package/dist/src/subgraphs/auth/utils/session.d.ts +22 -0
  41. package/dist/src/subgraphs/auth/utils/session.d.ts.map +1 -0
  42. package/dist/src/subgraphs/auth/utils/session.js +100 -0
  43. package/dist/src/subgraphs/auth/utils/user.d.ts +12 -0
  44. package/dist/src/subgraphs/auth/utils/user.d.ts.map +1 -0
  45. package/dist/src/subgraphs/auth/utils/user.js +26 -0
  46. package/dist/src/subgraphs/base/index.d.ts +16 -0
  47. package/dist/src/subgraphs/base/index.d.ts.map +1 -0
  48. package/dist/src/subgraphs/base/index.js +25 -0
  49. package/dist/src/subgraphs/drive/index.d.ts +11 -0
  50. package/dist/src/subgraphs/drive/index.d.ts.map +1 -0
  51. package/dist/src/subgraphs/drive/index.js +341 -0
  52. package/dist/src/subgraphs/drive/temp-hack-rwa-type-defs.d.ts +57 -0
  53. package/dist/src/subgraphs/drive/temp-hack-rwa-type-defs.d.ts.map +1 -0
  54. package/dist/src/subgraphs/drive/temp-hack-rwa-type-defs.js +1 -0
  55. package/dist/src/subgraphs/index.d.ts +10 -0
  56. package/dist/src/subgraphs/index.d.ts.map +1 -0
  57. package/dist/src/subgraphs/index.js +20 -0
  58. package/dist/src/subgraphs/manager.d.ts +23 -0
  59. package/dist/src/subgraphs/manager.d.ts.map +1 -0
  60. package/dist/src/subgraphs/manager.js +102 -0
  61. package/dist/src/subgraphs/system/env/getters.d.ts +2 -0
  62. package/dist/src/subgraphs/system/env/getters.d.ts.map +1 -0
  63. package/dist/src/subgraphs/system/env/getters.js +3 -0
  64. package/dist/src/subgraphs/system/env/index.d.ts +2 -0
  65. package/dist/src/subgraphs/system/env/index.d.ts.map +1 -0
  66. package/{src/subgraphs/system/env/index.ts → dist/src/subgraphs/system/env/index.js} +1 -3
  67. package/dist/src/subgraphs/system/index.d.ts +19 -0
  68. package/dist/src/subgraphs/system/index.d.ts.map +1 -0
  69. package/dist/src/subgraphs/system/index.js +63 -0
  70. package/dist/src/subgraphs/system/types.d.ts +5 -0
  71. package/dist/src/subgraphs/system/types.d.ts.map +1 -0
  72. package/dist/src/subgraphs/system/types.js +1 -0
  73. package/dist/src/subgraphs/types.d.ts +27 -0
  74. package/dist/src/subgraphs/types.d.ts.map +1 -0
  75. package/dist/src/subgraphs/types.js +1 -0
  76. package/dist/src/sync/utils.d.ts +13 -0
  77. package/dist/src/sync/utils.d.ts.map +1 -0
  78. package/dist/src/sync/utils.js +37 -0
  79. package/dist/src/types.d.ts +29 -0
  80. package/dist/src/types.d.ts.map +1 -0
  81. package/dist/src/types.js +1 -0
  82. package/dist/src/utils/create-schema.d.ts +7 -0
  83. package/dist/src/utils/create-schema.d.ts.map +1 -0
  84. package/dist/src/utils/create-schema.js +122 -0
  85. package/dist/src/utils/db.d.ts +4 -0
  86. package/dist/src/utils/db.d.ts.map +1 -0
  87. package/dist/src/utils/db.js +20 -0
  88. package/dist/src/utils/index.d.ts +3 -0
  89. package/dist/src/utils/index.d.ts.map +1 -0
  90. package/dist/src/utils/index.js +2 -0
  91. package/dist/tsconfig.tsbuildinfo +1 -0
  92. package/dist/vitest.config.d.ts +3 -0
  93. package/dist/vitest.config.d.ts.map +1 -0
  94. package/dist/vitest.config.js +24 -0
  95. package/package.json +18 -9
  96. package/CHANGELOG.md +0 -39
  97. package/dist/index.js.map +0 -1
  98. package/src/index.ts +0 -7
  99. package/src/processors/analytics-processor.ts +0 -18
  100. package/src/processors/index.ts +0 -4
  101. package/src/processors/manager.ts +0 -75
  102. package/src/processors/operational-processor.ts +0 -20
  103. package/src/processors/processor.ts +0 -75
  104. package/src/server.ts +0 -65
  105. package/src/subgraphs/analytics/index.ts +0 -119
  106. package/src/subgraphs/auth/env/getters.ts +0 -30
  107. package/src/subgraphs/auth/index.ts +0 -321
  108. package/src/subgraphs/auth/types.ts +0 -39
  109. package/src/subgraphs/auth/utils/helpers.ts +0 -132
  110. package/src/subgraphs/auth/utils/session.ts +0 -144
  111. package/src/subgraphs/auth/utils/user.ts +0 -40
  112. package/src/subgraphs/base/index.ts +0 -34
  113. package/src/subgraphs/drive/index.ts +0 -434
  114. package/src/subgraphs/drive/temp-hack-rwa-type-defs.ts +0 -39
  115. package/src/subgraphs/index.ts +0 -24
  116. package/src/subgraphs/manager.ts +0 -128
  117. package/src/subgraphs/system/env/getters.ts +0 -7
  118. package/src/subgraphs/system/index.ts +0 -73
  119. package/src/subgraphs/system/types.ts +0 -5
  120. package/src/subgraphs/types.ts +0 -29
  121. package/src/sync/utils.ts +0 -85
  122. package/src/types.ts +0 -43
  123. package/src/utils/create-schema.ts +0 -160
  124. package/src/utils/db.ts +0 -26
  125. package/src/utils/index.ts +0 -2
  126. package/test/benchmarks/load.bench.ts +0 -78
  127. package/test/benchmarks/sync.bench.ts +0 -151
  128. package/test/data/BlocktowerAndromeda.zip +0 -0
  129. package/test/router.test.ts +0 -48
  130. package/tsconfig.json +0 -21
  131. package/tsdoc.json +0 -3
  132. package/tsup.config.ts +0 -17
  133. package/types.d.ts +0 -5
  134. package/vitest.config.ts +0 -28
@@ -1,321 +0,0 @@
1
- import { GraphQLResolverMap } from "@apollo/subgraph/dist/schema-helper";
2
- import { generateUUID } from "document-drive";
3
- import { GraphQLError } from "graphql";
4
- import { gql } from "graphql-tag";
5
- import { SiweMessage } from "siwe";
6
- import { Db } from "src/types";
7
- import { Subgraph } from "../base";
8
- import { Context } from "../types";
9
- import { AuthContext, Challenge, Session, SessionInput } from "./types";
10
- import { generateTokenAndSession } from "./utils/helpers";
11
- import {
12
- authenticate,
13
- createAuthenticationSession,
14
- verifySignature,
15
- } from "./utils/session";
16
- import { getUser, upsertUser } from "./utils/user";
17
-
18
- export class AuthSubgraph extends Subgraph {
19
- name = "auth";
20
- typeDefs = gql`
21
- type Query {
22
- me: User
23
- sessions: [Session!]!
24
- }
25
-
26
- type Mutation {
27
- createChallenge(address: String!): Challenge
28
- solveChallenge(nonce: String!, signature: String!): SessionOutput
29
- createSession(session: SessionInput!): SessionOutput
30
- revokeSession(sessionId: String!): SessionOutput
31
- }
32
-
33
- type User {
34
- address: String!
35
- createdAt: DateTime!
36
- }
37
-
38
- type Challenge {
39
- nonce: String!
40
- message: String!
41
- hex: String!
42
- }
43
-
44
- type SessionOutput {
45
- id: ID!
46
- token: String
47
- }
48
-
49
- type Session {
50
- id: ID!
51
- userId: String!
52
- address: String!
53
- expiresAt: DateTime!
54
- createdAt: DateTime!
55
- updatedAt: DateTime!
56
- referenceTokenId: String!
57
- createdBy: String!
58
- referenceExpiryDate: DateTime
59
- isUserCreated: Boolean!
60
- name: String
61
- allowedOrigins: String
62
- revokedAt: DateTime
63
- }
64
-
65
- input SessionInput {
66
- expiryDurationSeconds: Int
67
- name: String!
68
- allowedOrigins: String!
69
- }
70
- `;
71
-
72
- resolvers: GraphQLResolverMap<AuthContext> = {
73
- Query: {
74
- me: async (_, __, ctx) => {
75
- const db = ctx.db as Db;
76
- const session = await authenticate(ctx);
77
- const user = await getUser(db, session.createdBy);
78
- return user;
79
- },
80
- sessions: async (_: unknown, __: unknown, ctx: Context) => {
81
- const session = await authenticate(ctx);
82
- const db = ctx.db as Db;
83
- const sessions = await db<Session>("Session")
84
- .select()
85
- .where("createdBy", session.createdBy)
86
- .orderBy("createdAt", "desc");
87
- return sessions;
88
- },
89
- },
90
- Mutation: {
91
- createChallenge: async (
92
- _: unknown,
93
- { address }: { address: string },
94
- ctx: Context,
95
- ) => {
96
- const db = ctx.db as Db;
97
- const { API_ORIGIN } = process.env;
98
-
99
- const origin = API_ORIGIN ?? "http://localhost:3000";
100
- const domain = new URL(origin).hostname;
101
-
102
- if (!domain) {
103
- throw new GraphQLError("Invalid origin");
104
- }
105
-
106
- const nonce = generateUUID().replace(/-/g, "");
107
-
108
- const message = new SiweMessage({
109
- address,
110
- nonce,
111
- uri: origin,
112
- domain,
113
- version: "1",
114
- chainId: 1,
115
- }).prepareMessage();
116
- const textToHex = (textMessage: string) =>
117
- `0x${Buffer.from(textMessage, "utf8").toString("hex")}`;
118
- if (!message || typeof message !== "string") {
119
- throw new GraphQLError("Failed to create challenge");
120
- }
121
- const hexMessage = textToHex(message);
122
-
123
- await db("Challenge").insert({
124
- nonce,
125
- message,
126
- updatedAt: new Date().toISOString(),
127
- });
128
-
129
- return {
130
- nonce,
131
- message,
132
- hex: hexMessage,
133
- };
134
- },
135
- solveChallenge: async (
136
- _: unknown,
137
- { nonce, signature }: { nonce: string; signature: string },
138
- ctx: Context,
139
- ) => {
140
- const db = ctx.db as Db;
141
- const data = await db.transaction(async (tx) => {
142
- const [challenge] = await tx<Challenge>("Challenge")
143
- .select()
144
- .where("nonce", nonce);
145
-
146
- // check that challenge with this nonce exists
147
- if (!challenge) {
148
- throw new GraphQLError("The nonce is not known");
149
- }
150
-
151
- // check that challenge was not used
152
- if (challenge.signature) {
153
- throw new GraphQLError("The signature was already used");
154
- }
155
-
156
- // verify signature
157
-
158
- const parsedMessage = new SiweMessage(challenge.message);
159
- try {
160
- await verifySignature(parsedMessage, signature);
161
- } catch (error) {
162
- throw new GraphQLError("Signature validation has failed");
163
- }
164
-
165
- // mark challenge as used
166
- await tx<Challenge>("Challenge")
167
- .update({
168
- signature,
169
- })
170
- .where("nonce", nonce);
171
-
172
- // create user and session
173
- const user = await upsertUser(db, {
174
- address: parsedMessage.address as `0x${string}`,
175
- networkId: "1",
176
- chainId: 1,
177
- });
178
-
179
- if (!user) {
180
- throw new GraphQLError("User not found");
181
- }
182
-
183
- const tokenAndSession = await createAuthenticationSession(
184
- db,
185
- user.address,
186
- );
187
-
188
- return tokenAndSession;
189
- });
190
-
191
- return data;
192
- },
193
- createSession: async (
194
- _: unknown,
195
- { session }: { session: SessionInput },
196
- ctx: Context,
197
- ) => {
198
- const db = ctx.db as Db;
199
- const sessionAuth = await authenticate(ctx);
200
- const tokenAndSession = await generateTokenAndSession(
201
- db,
202
- session,
203
- sessionAuth.createdBy,
204
- sessionAuth.isUserCreated,
205
- );
206
- if (!tokenAndSession) {
207
- throw new GraphQLError("Failed to create session");
208
- }
209
- return tokenAndSession;
210
- },
211
- revokeSession: async (
212
- _: unknown,
213
- { sessionId }: { sessionId: string },
214
- ctx: Context,
215
- ): Promise<{ id: string }> => {
216
- const user = await authenticate(ctx);
217
- const db = ctx.db as Db;
218
- const [session] = await db<Session>("Session").select().where({
219
- id: sessionId,
220
- createdBy: user.createdBy,
221
- });
222
-
223
- if (!session) {
224
- throw new GraphQLError("Session not found", {
225
- extensions: { code: "SESSION_NOT_FOUND" },
226
- });
227
- }
228
- if (session.revokedAt !== null) {
229
- throw new GraphQLError("Session already revoked", {
230
- extensions: { code: "SESSION_ALREADY_REVOKED" },
231
- });
232
- }
233
-
234
- await db<Session>("Session")
235
- .update({
236
- revokedAt: new Date().toISOString(),
237
- })
238
- .where({
239
- id: sessionId,
240
- createdBy: user.createdBy,
241
- });
242
-
243
- return { id: session.id };
244
- },
245
- },
246
- };
247
-
248
- async onSetup() {
249
- await super.onSetup();
250
- await this.#createTables();
251
- this.subgraphManager.setAdditionalContextFields({
252
- session: async (ctx: Context) => {
253
- const bearerToken = ctx.headers.authorization?.split(" ")[1];
254
- if (!bearerToken) {
255
- return null;
256
- }
257
-
258
- // @todo: optimize and cache this
259
- const db = ctx.db as Db;
260
- const [session] = await db<Session>("Session")
261
- .select()
262
- .where({
263
- referenceTokenId: bearerToken,
264
- })
265
- .limit(1);
266
-
267
- return session;
268
- },
269
- });
270
- }
271
-
272
- async #createTables() {
273
- if (!(await this.operationalStore.schema.hasTable("User"))) {
274
- await this.operationalStore.schema.createTable("User", (table) => {
275
- table.string("address").primary().notNullable();
276
- table.timestamp("createdAt").notNullable().defaultTo(`now()`);
277
- table.timestamp("updatedAt").notNullable().defaultTo(`now()`);
278
- });
279
- }
280
-
281
- if (!(await this.operationalStore.schema.hasTable("Session"))) {
282
- await this.operationalStore.schema.createTable("Session", (table) => {
283
- table.string("id").primary().notNullable();
284
- table.timestamp("createdAt").notNullable().defaultTo(`now()`);
285
- table.string("createdBy").notNullable();
286
- table.string("referenceExpiryDate");
287
- table.string("name");
288
- table.string("revokedAt");
289
- table.string("referenceTokenId").notNullable();
290
- table.boolean("isUserCreated").notNullable().defaultTo(false);
291
- table.string("allowedOrigins").notNullable();
292
-
293
- table.index(["createdBy", "id"], "Session_createdBy_id_key", {
294
- indexType: "UNIQUE",
295
- storageEngineIndexType: "btree",
296
- });
297
-
298
- table
299
- .foreign("createdBy")
300
- .references("User.address")
301
- .onDelete("cascade")
302
- .onUpdate("cascade");
303
- });
304
- }
305
-
306
- if (!(await this.operationalStore.schema.hasTable("Challenge"))) {
307
- await this.operationalStore.schema.createTable("Challenge", (table) => {
308
- table.string("nonce").primary().notNullable();
309
- table.string("message").notNullable();
310
- table.string("signature");
311
- table.timestamp("createdAt").notNullable().defaultTo(`now()`);
312
- table.timestamp("updatedAt").notNullable();
313
-
314
- table.index("nonce", "Challenge_message_key", {
315
- indexType: "UNIQUE",
316
- storageEngineIndexType: "btree",
317
- });
318
- });
319
- }
320
- }
321
- }
@@ -1,39 +0,0 @@
1
- import { Context } from "../types";
2
-
3
- export interface SessionInput {
4
- name: string;
5
- allowedOrigins: string[];
6
- expiresAt?: string;
7
- }
8
-
9
- export interface SessionOutput {
10
- session: Session;
11
- token: string;
12
- }
13
-
14
- export interface Session {
15
- id: string;
16
- userId: string;
17
- address: string;
18
- name?: string;
19
- expiresAt: string;
20
- createdAt: string;
21
- updatedAt: string;
22
- revokedAt: string | null;
23
- allowedOrigins: string;
24
- referenceExpiryDate: string;
25
- referenceTokenId: string;
26
- isUserCreated: boolean;
27
- createdBy: string;
28
- }
29
-
30
- export interface Challenge {
31
- id: string;
32
- nonce: string;
33
- signature: string;
34
- message: string;
35
- }
36
-
37
- export type AuthContext = Context & {
38
- session: Session;
39
- };
@@ -1,132 +0,0 @@
1
- import { randomUUID } from "crypto";
2
- import { GraphQLError } from "graphql";
3
- import jwt from "jsonwebtoken";
4
- import ms from "ms";
5
- import wildcard from "wildcard-match";
6
- import z from "zod";
7
- import { Db } from "../../../utils/db";
8
- import { JWT_EXPIRATION_PERIOD, JWT_SECRET } from "../env";
9
- import { Session, SessionInput } from "../types";
10
- const jwtSchema = z.object({
11
- sessionId: z.string(),
12
- exp: z.optional(z.number()),
13
- });
14
-
15
- export const formatToken = (token: string) =>
16
- `${token.slice(0, 4)}...${token.slice(-4)}`;
17
-
18
- /** Generate a JWT token
19
- * - If expiryDurationSeconds is null, the token will never expire
20
- * - If expiryDurationSeconds is undefined, the token will expire after the default expiry period
21
- */
22
- const generateToken = (
23
- sessionId: string,
24
- expiryDurationSeconds?: number | null,
25
- ): string => {
26
- if (expiryDurationSeconds === null) {
27
- return jwt.sign({ sessionId }, JWT_SECRET);
28
- }
29
-
30
- const expiresIn = expiryDurationSeconds
31
- ? ms(expiryDurationSeconds * 1000)
32
- : (JWT_EXPIRATION_PERIOD ?? 3600);
33
- return jwt.sign({ sessionId }, JWT_SECRET, { expiresIn });
34
- };
35
-
36
- const getExpiryDateFromToken = (token: string): Date | null => {
37
- const { exp } = jwtSchema.parse(jwt.verify(token, JWT_SECRET));
38
- if (!exp) {
39
- return null;
40
- }
41
- return new Date(exp * 1000);
42
- };
43
-
44
- export const verifyToken = (
45
- token: string,
46
- ): { sessionId: string } | undefined => {
47
- const verified = jwt.verify(token, JWT_SECRET, (err, decoded) => {
48
- if (err) {
49
- throw new GraphQLError(
50
- err.name === "TokenExpiredError"
51
- ? "Token expired"
52
- : "Invalid authentication token",
53
- { extensions: { code: "AUTHENTICATION_TOKEN_ERROR" } },
54
- );
55
- }
56
- return decoded;
57
- }) as { sessionId: string } | undefined;
58
- if (!verified) {
59
- return undefined;
60
- }
61
- const validated = jwtSchema.parse(verified);
62
- return validated;
63
- };
64
-
65
- function parseOriginMarkup(originParam: string): string {
66
- if (originParam === "*") {
67
- return "*";
68
- }
69
- const trimmedOriginParam = originParam.trim();
70
- const origins = trimmedOriginParam.split(",").map((origin) => origin.trim());
71
- origins.forEach((origin) => {
72
- if (!origin.startsWith("http://") && !origin.startsWith("https://")) {
73
- throw new GraphQLError("Origin must start with 'http://' or 'https://'", {
74
- extensions: { code: "INVALID_ORIGIN_PROTOCOL" },
75
- });
76
- }
77
- });
78
- return origins.join(",");
79
- }
80
-
81
- export function validateOriginAgainstAllowed(
82
- allowedOrigins: string,
83
- originReceived?: string,
84
- ) {
85
- if (allowedOrigins === "*") {
86
- return;
87
- }
88
- if (!originReceived) {
89
- throw new GraphQLError("Origin not provided", {
90
- extensions: { code: "ORIGIN_HEADER_MISSING" },
91
- });
92
- }
93
- const allowedOriginsSplit = allowedOrigins.split(",");
94
- if (!wildcard(allowedOriginsSplit)(originReceived)) {
95
- throw new GraphQLError(
96
- `Access denied due to origin restriction: ${allowedOrigins}, ${originReceived}`,
97
- {
98
- extensions: { code: "ORIGIN_FORBIDDEN" },
99
- },
100
- );
101
- }
102
- }
103
-
104
- export const generateTokenAndSession = async (
105
- db: Db,
106
- session: SessionInput,
107
- userId: string,
108
- isUserCreated: boolean,
109
- ) => {
110
- const sessionId = randomUUID();
111
- const generatedToken = generateToken(sessionId, Number(session.expiresAt));
112
- const referenceExpiryDate = getExpiryDateFromToken(generatedToken);
113
- const referenceTokenId = formatToken(generatedToken);
114
- const allowedOrigins = parseOriginMarkup(
115
- Array.isArray(session.allowedOrigins)
116
- ? session.allowedOrigins.join(",")
117
- : session.allowedOrigins,
118
- );
119
- const createdSession = await db<Session>("Session").insert({
120
- id: sessionId,
121
- name: session.name,
122
- allowedOrigins,
123
- referenceExpiryDate: referenceExpiryDate?.toISOString(),
124
- referenceTokenId,
125
- isUserCreated: isUserCreated,
126
- createdBy: userId,
127
- });
128
- return {
129
- token: generatedToken,
130
- session: createdSession,
131
- };
132
- };
@@ -1,144 +0,0 @@
1
- import { GraphQLError } from "graphql";
2
- import ms from "ms";
3
- import { SiweMessage } from "siwe";
4
- import { JWT_EXPIRATION_PERIOD } from "../env";
5
- import { Session } from "../types";
6
- import {
7
- generateTokenAndSession,
8
- validateOriginAgainstAllowed,
9
- verifyToken,
10
- } from "./helpers";
11
- import { Db } from "../../../types";
12
- import { Context } from "src/subgraphs/types";
13
-
14
- export const createAuthenticationSession = async (
15
- db: Db,
16
- userId: string,
17
- allowedOrigins = ["*"],
18
- ) => {
19
- return generateTokenAndSession(
20
- db,
21
- {
22
- expiresAt: new Date(
23
- new Date().getTime() + ms(JWT_EXPIRATION_PERIOD),
24
- ).toISOString(),
25
- name: "Sign in/Sign up",
26
- allowedOrigins,
27
- },
28
- userId,
29
- true,
30
- );
31
- };
32
-
33
- export const createCustomSession = async (
34
- db: Db,
35
- userId: string,
36
- session: {
37
- expiryDurationSeconds?: number | null;
38
- name: string;
39
- allowedOrigins: string[];
40
- },
41
- isUserCreated = false,
42
- ) => {
43
- return generateTokenAndSession(db, session, userId, isUserCreated);
44
- };
45
-
46
- export const listSessions = async (db: Db, userId: string) => {
47
- return db<Session>("Session").select().where("createdBy", userId);
48
- };
49
-
50
- export const revoke = async (db: Db, sessionId: string, userId: string) => {
51
- const [session] = await db<Session>("Session").select().where({
52
- id: sessionId,
53
- userId,
54
- });
55
-
56
- if (!session) {
57
- throw new GraphQLError("Session not found", {
58
- extensions: { code: "SESSION_NOT_FOUND" },
59
- });
60
- }
61
- if (session.revokedAt !== null) {
62
- throw new GraphQLError("Session already revoked", {
63
- extensions: { code: "SESSION_ALREADY_REVOKED" },
64
- });
65
- }
66
- await db<Session>("Session")
67
- .update({
68
- revokedAt: new Date().toISOString(),
69
- })
70
- .where({
71
- id: sessionId,
72
- userId,
73
- });
74
- };
75
-
76
- export const authenticate = async (context: Context) => {
77
- const authorization = context.headers.authorization;
78
- const db = context.db as Db;
79
- if (!authorization) {
80
- throw new GraphQLError("Not authenticated", {
81
- extensions: { code: "NOT_AUTHENTICATED" },
82
- });
83
- }
84
- const token = authorization.replace("Bearer ", "");
85
- const origin = context.headers.origin;
86
- const session = await getSessionByToken(db, origin, token);
87
- return session;
88
- };
89
-
90
- export const getSessionByToken = async (
91
- db: Db,
92
- origin?: string,
93
- token?: string,
94
- ) => {
95
- if (!token) {
96
- throw new GraphQLError("Not authenticated", {
97
- extensions: { code: "NOT_AUTHENTICATED" },
98
- });
99
- }
100
- const verificationTokenResult = verifyToken(token);
101
- if (!verificationTokenResult) {
102
- throw new GraphQLError("Invalid token", {
103
- extensions: { code: "INVALID_TOKEN" },
104
- });
105
- }
106
- const { sessionId } = verificationTokenResult;
107
- const [session] = await db<Session>("Session").select().where({
108
- id: sessionId,
109
- });
110
- if (!session) {
111
- throw new GraphQLError("Session not found", {
112
- extensions: { code: "SESSION_NOT_FOUND" },
113
- });
114
- }
115
- if (session.revokedAt) {
116
- throw new GraphQLError("Session expired", {
117
- extensions: { code: "SESSION_EXPIRED" },
118
- });
119
- }
120
- if (
121
- origin &&
122
- (!session.allowedOrigins ||
123
- session.allowedOrigins === "*" ||
124
- session.allowedOrigins.includes(origin))
125
- ) {
126
- validateOriginAgainstAllowed(session.allowedOrigins, origin);
127
- }
128
- return session;
129
- };
130
-
131
- export const verifySignature = async (
132
- parsedMessage: SiweMessage,
133
- signature: string,
134
- ) => {
135
- try {
136
- const response = await parsedMessage.verify({
137
- time: new Date().toISOString(),
138
- signature,
139
- });
140
- return response;
141
- } catch (error) {
142
- throw new GraphQLError("Invalid signature");
143
- }
144
- };
@@ -1,40 +0,0 @@
1
- import { GraphQLError } from "graphql";
2
- import { Db } from "../../../utils/db";
3
-
4
- interface User {
5
- address: string;
6
- createdAt?: string;
7
- updatedAt?: string;
8
- networkId: string;
9
- chainId: number;
10
- }
11
- export const upsertUser = async (db: Db, user: User) => {
12
- const { AUTH_SIGNUP_DISABLED } = process.env;
13
- if (AUTH_SIGNUP_DISABLED) {
14
- throw new GraphQLError("Sign up is disabled");
15
- }
16
-
17
- const [existingUser] = await db<User>("User")
18
- .select()
19
- .where("address", user.address);
20
-
21
- if (existingUser) {
22
- return existingUser;
23
- }
24
-
25
- const date = new Date().toISOString();
26
- const [newUser] = await db<User>("User")
27
- .insert({
28
- address: user.address,
29
- updatedAt: date,
30
- createdAt: date,
31
- })
32
- .returning("*");
33
-
34
- return newUser;
35
- };
36
-
37
- export const getUser = async (db: Db, address: string) => {
38
- const [user] = await db<User>("User").select().where("address", address);
39
- return user;
40
- };
@@ -1,34 +0,0 @@
1
- import { ISubgraph } from "../types";
2
- import { DocumentNode } from "graphql";
3
- import { IDocumentDriveServer } from "document-drive";
4
- import { SubgraphArgs } from "../types";
5
- import { GraphQLResolverMap } from "@apollo/subgraph/dist/schema-helper";
6
- import { gql } from "graphql-tag";
7
- import { Context } from "../types";
8
- import { Db } from "src/types";
9
- import { SubgraphManager } from "../manager";
10
-
11
- export class Subgraph implements ISubgraph {
12
- name = "example";
13
- resolvers: Record<string, any> = {
14
- Query: {
15
- hello: () => this.name,
16
- },
17
- };
18
- typeDefs: DocumentNode = gql`
19
- type Query {
20
- hello: String
21
- }
22
- `;
23
- reactor: IDocumentDriveServer;
24
- subgraphManager: SubgraphManager;
25
- operationalStore: Db;
26
- constructor(args: SubgraphArgs) {
27
- this.reactor = args.reactor;
28
- this.subgraphManager = args.subgraphManager;
29
- this.operationalStore = args.operationalStore;
30
- }
31
- async onSetup() {
32
- // noop
33
- }
34
- }