-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodegen.ts
More file actions
160 lines (139 loc) · 4.42 KB
/
codegen.ts
File metadata and controls
160 lines (139 loc) · 4.42 KB
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
158
159
160
/// <reference types="node" />
import { createHmac, randomUUID } from 'crypto';
import { readFileSync } from 'fs';
import { join } from 'path';
import type { CodegenConfig } from '@graphql-codegen/cli';
type JwtConfig = {
Secret?: string;
Issuer?: string;
Audience?: string;
ExpiryMinutes?: number;
};
const schemaUrl = process.env.GRAPHQL_SCHEMA_URL ?? 'http://127.0.0.1:5095/graphql';
const defaultEmail = process.env.GRAPHQL_CODEGEN_EMAIL ?? 'codegen@banktracking.local';
const defaultUserId = process.env.GRAPHQL_CODEGEN_ACCOUNT_ID ?? '0';
const defaultExpiryMinutes = 60;
const loadJwtConfig = (): JwtConfig => {
const override: JwtConfig = {
Secret: process.env.GRAPHQL_JWT_SECRET,
Issuer: process.env.GRAPHQL_JWT_ISSUER,
Audience: process.env.GRAPHQL_JWT_AUDIENCE,
ExpiryMinutes: process.env.GRAPHQL_JWT_EXPIRY
? Number.parseInt(process.env.GRAPHQL_JWT_EXPIRY, 10)
: undefined,
};
if (override.Secret) {
return override;
}
try {
const configPath = join(
__dirname,
'..',
'PhantomDave.BankTracking.Api',
'appsettings.Development.json',
);
const fileContent = readFileSync(configPath, 'utf-8');
const parsed = JSON.parse(fileContent);
const jwt = (parsed?.Jwt ?? {}) as JwtConfig;
return {
Secret: jwt.Secret ?? override.Secret,
Issuer: jwt.Issuer ?? override.Issuer,
Audience: jwt.Audience ?? override.Audience,
ExpiryMinutes: jwt.ExpiryMinutes ?? override.ExpiryMinutes,
};
} catch (error) {
console.warn('Warning: Unable to read appsettings.Development.json for JWT settings.', error);
return override;
}
};
const toBase64Url = (value: string) => Buffer.from(value).toString('base64url');
const buildJwt = (jwtConfig: JwtConfig): string | undefined => {
const secret = jwtConfig.Secret;
if (!secret) {
console.warn('Warning: Missing JWT secret; falling back to unauthenticated schema fetch.');
return undefined;
}
const nowSeconds = Math.floor(Date.now() / 1000);
const expiryMinutes = Number.isFinite(jwtConfig.ExpiryMinutes)
? Number(jwtConfig.ExpiryMinutes)
: defaultExpiryMinutes;
const payloadBase = {
iss: jwtConfig.Issuer,
aud: jwtConfig.Audience,
exp: nowSeconds + expiryMinutes * 60,
nbf: nowSeconds - 5,
iat: nowSeconds,
jti: randomUUID(),
sub: defaultEmail,
'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier': defaultUserId,
'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name': defaultEmail,
};
const payload = Object.fromEntries(
Object.entries(payloadBase).filter(([, value]) => value !== undefined && value !== ''),
);
const header = {
alg: 'HS256',
typ: 'JWT',
};
const encodedHeader = toBase64Url(JSON.stringify(header));
const encodedPayload = toBase64Url(JSON.stringify(payload));
const signingInput = `${encodedHeader}.${encodedPayload}`;
const signature = createHmac('sha256', secret).update(signingInput).digest('base64url');
return `${signingInput}.${signature}`;
};
const getAuthToken = (): string | undefined => {
if (process.env.GRAPHQL_AUTH_TOKEN) {
return process.env.GRAPHQL_AUTH_TOKEN;
}
const jwtConfig = loadJwtConfig();
return buildJwt(jwtConfig);
};
const buildSchemaConfig = (token: string | undefined): CodegenConfig['schema'] => {
if (!token) {
return schemaUrl;
}
return {
[schemaUrl]: {
headers: {
Authorization: `Bearer ${token}`,
},
},
};
};
const token = getAuthToken();
if (!token) {
console.warn(
'Warning: Proceeding without Authorization header. GraphQL code generation may fail if the endpoint requires authentication.',
);
}
const config: CodegenConfig = {
schema: process.env.USE_LOCAL_SCHEMA === 'true' ? './schema.graphql' : buildSchemaConfig(token),
documents: ['src/**/*.graphql'],
generates: {
'./src/generated/graphql.ts': {
plugins: ['typescript', 'typescript-operations', 'typescript-apollo-angular'],
config: {
addExplicitOverride: true,
strictScalars: true,
scalars: {
DateTime: 'string',
Decimal: 'number',
UUID: 'string',
Long: 'number',
},
namingConvention: {
enumValues: 'keep',
},
},
},
'./schema.graphql': {
plugins: ['schema-ast'],
config: {
includeDirectives: true,
},
},
},
watch: false,
ignoreNoDocuments: true,
};
export default config;