-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
debuglogs.ts
191 lines (168 loc) · 5.26 KB
/
debuglogs.ts
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
// Copyright 2018-2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import { memoize, sortBy } from 'lodash';
import os from 'os';
import { ipcRenderer as ipc } from 'electron';
import { z } from 'zod';
import FormData from 'form-data';
import { gzip } from 'zlib';
import pify from 'pify';
import type { Response } from 'got';
import got from 'got';
import { getUserAgent } from '../util/getUserAgent';
import { maybeParseUrl } from '../util/url';
import * as log from './log';
import { reallyJsonStringify } from '../util/reallyJsonStringify';
import type { FetchLogIpcData, LogEntryType } from './shared';
import {
LogLevel,
getLogLevelString,
isFetchLogIpcData,
isLogEntry,
levelMaxLength,
} from './shared';
import { redactAll } from '../util/privacy';
import { getEnvironment } from '../environment';
const BASE_URL = 'https://debuglogs.org';
const tokenBodySchema = z
.object({
fields: z.record(z.unknown()),
url: z.string(),
})
.nonstrict();
const parseTokenBody = (
rawBody: unknown
): { fields: Record<string, unknown>; url: string } => {
const body = tokenBodySchema.parse(rawBody);
const parsedUrl = maybeParseUrl(body.url);
if (!parsedUrl) {
throw new Error("Token body's URL was not a valid URL");
}
if (parsedUrl.protocol !== 'https:') {
throw new Error("Token body's URL was not HTTPS");
}
return body;
};
export const upload = async (
content: string,
appVersion: string
): Promise<string> => {
const headers = { 'User-Agent': getUserAgent(appVersion) };
const signedForm = await got.get(BASE_URL, { responseType: 'json', headers });
const { fields, url } = parseTokenBody(signedForm.body);
const uploadKey = `${fields.key}.gz`;
const form = new FormData();
// The API expects `key` to be the first field:
form.append('key', uploadKey);
Object.entries(fields)
.filter(([key]) => key !== 'key')
.forEach(([key, value]) => {
form.append(key, value);
});
const contentBuffer = await pify(gzip)(Buffer.from(content, 'utf8'));
const contentType = 'application/gzip';
form.append('Content-Type', contentType);
form.append('file', contentBuffer, {
contentType,
filename: `signal-desktop-debug-log-${appVersion}.txt.gz`,
});
log.info('Debug log upload starting...');
try {
const { statusCode, body } = await got.post(url, { headers, body: form });
if (statusCode !== 204) {
throw new Error(
`Failed to upload to S3, got status ${statusCode}, body '${body}'`
);
}
} catch (error) {
const response = error.response as Response<string>;
throw new Error(
`Got threw on upload to S3, got status ${response?.statusCode}, body '${response?.body}' `
);
}
log.info('Debug log upload complete.');
return `${BASE_URL}/${uploadKey}`;
};
// The mechanics of preparing a log for publish
const headerSectionTitle = (title: string) => `========= ${title} =========`;
const headerSection = (
title: string,
data: Readonly<Record<string, unknown>>
): string => {
const sortedEntries = sortBy(Object.entries(data), ([key]) => key);
return [
headerSectionTitle(title),
...sortedEntries.map(
([key, value]) => `${key}: ${redactAll(String(value))}`
),
'',
].join('\n');
};
const getHeader = (
{
capabilities,
remoteConfig,
statistics,
user,
}: Omit<FetchLogIpcData, 'logEntries'>,
nodeVersion: string,
appVersion: string
): string =>
[
headerSection('System info', {
Time: Date.now(),
'User agent': window.navigator.userAgent,
'Node version': nodeVersion,
Environment: getEnvironment(),
'App version': appVersion,
'OS version': os.version(),
}),
headerSection('User info', user),
headerSection('Capabilities', capabilities),
headerSection('Remote config', remoteConfig),
headerSection('Statistics', statistics),
headerSectionTitle('Logs'),
].join('\n');
const getLevel = memoize((level: LogLevel): string => {
const text = getLogLevelString(level);
return text.toUpperCase().padEnd(levelMaxLength, ' ');
});
function formatLine(mightBeEntry: unknown): string {
const entry: LogEntryType = isLogEntry(mightBeEntry)
? mightBeEntry
: {
level: LogLevel.Error,
msg: `Invalid IPC data when fetching logs. Here's what we could recover: ${reallyJsonStringify(
mightBeEntry
)}`,
time: new Date().toISOString(),
};
return `${getLevel(entry.level)} ${entry.time} ${entry.msg}`;
}
export function fetch(
nodeVersion: string,
appVersion: string
): Promise<string> {
return new Promise(resolve => {
ipc.send('fetch-log');
ipc.on('fetched-log', (_event, data: unknown) => {
let header: string;
let body: string;
if (isFetchLogIpcData(data)) {
const { logEntries } = data;
header = getHeader(data, nodeVersion, appVersion);
body = logEntries.map(formatLine).join('\n');
} else {
header = headerSectionTitle('Partial logs');
const entry: LogEntryType = {
level: LogLevel.Error,
msg: 'Invalid IPC data when fetching logs; dropping all logs',
time: new Date().toISOString(),
};
body = formatLine(entry);
}
const result = `${header}\n${body}`;
resolve(result);
});
});
}