-
Notifications
You must be signed in to change notification settings - Fork 435
/
decipher.go
285 lines (237 loc) · 6.7 KB
/
decipher.go
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package youtube
import (
"bytes"
"context"
"errors"
"fmt"
"net/url"
"regexp"
"strconv"
"github.com/dop251/goja"
)
func (c *Client) decipherURL(ctx context.Context, videoID string, cipher string) (string, error) {
params, err := url.ParseQuery(cipher)
if err != nil {
return "", err
}
uri, err := url.Parse(params.Get("url"))
if err != nil {
return "", err
}
query := uri.Query()
config, err := c.getPlayerConfig(ctx, videoID)
if err != nil {
return "", err
}
// decrypt s-parameter
bs, err := config.decrypt([]byte(params.Get("s")))
if err != nil {
return "", err
}
query.Add(params.Get("sp"), string(bs))
query, err = c.decryptNParam(config, query)
if err != nil {
return "", err
}
uri.RawQuery = query.Encode()
return uri.String(), nil
}
// see https://github.com/kkdai/youtube/pull/244
func (c *Client) unThrottle(ctx context.Context, videoID string, urlString string) (string, error) {
config, err := c.getPlayerConfig(ctx, videoID)
if err != nil {
return "", err
}
uri, err := url.Parse(urlString)
if err != nil {
return "", err
}
// for debugging
if artifactsFolder != "" {
writeArtifact("video-"+videoID+".url", []byte(uri.String()))
}
query, err := c.decryptNParam(config, uri.Query())
if err != nil {
return "", err
}
uri.RawQuery = query.Encode()
return uri.String(), nil
}
func (c *Client) decryptNParam(config playerConfig, query url.Values) (url.Values, error) {
// decrypt n-parameter
nSig := query.Get("v")
log := Logger.With("n", nSig)
if nSig != "" {
nDecoded, err := config.decodeNsig(nSig)
if err != nil {
return nil, fmt.Errorf("unable to decode nSig: %w", err)
}
query.Set("v", nDecoded)
log = log.With("decoded", nDecoded)
}
log.Debug("nParam")
return query, nil
}
const (
jsvarStr = "[a-zA-Z_\\$][a-zA-Z_0-9]*"
reverseStr = ":function\\(a\\)\\{" +
"(?:return )?a\\.reverse\\(\\)" +
"\\}"
spliceStr = ":function\\(a,b\\)\\{" +
"a\\.splice\\(0,b\\)" +
"\\}"
swapStr = ":function\\(a,b\\)\\{" +
"var c=a\\[0\\];a\\[0\\]=a\\[b(?:%a\\.length)?\\];a\\[b(?:%a\\.length)?\\]=c(?:;return a)?" +
"\\}"
)
var (
nFunctionNameRegexp = regexp.MustCompile("\\.get\\(\"n\"\\)\\)&&\\(b=([a-zA-Z0-9$]{0,3})\\[(\\d+)\\](.+)\\|\\|([a-zA-Z0-9]{0,3})")
actionsObjRegexp = regexp.MustCompile(fmt.Sprintf(
"var (%s)=\\{((?:(?:%s%s|%s%s|%s%s),?\\n?)+)\\};", jsvarStr, jsvarStr, swapStr, jsvarStr, spliceStr, jsvarStr, reverseStr))
actionsFuncRegexp = regexp.MustCompile(fmt.Sprintf(
"function(?: %s)?\\(a\\)\\{"+
"a=a\\.split\\(\"\"\\);\\s*"+
"((?:(?:a=)?%s\\.%s\\(a,\\d+\\);)+)"+
"return a\\.join\\(\"\"\\)"+
"\\}", jsvarStr, jsvarStr, jsvarStr))
reverseRegexp = regexp.MustCompile(fmt.Sprintf("(?m)(?:^|,)(%s)%s", jsvarStr, reverseStr))
spliceRegexp = regexp.MustCompile(fmt.Sprintf("(?m)(?:^|,)(%s)%s", jsvarStr, spliceStr))
swapRegexp = regexp.MustCompile(fmt.Sprintf("(?m)(?:^|,)(%s)%s", jsvarStr, swapStr))
)
func (config playerConfig) decodeNsig(encoded string) (string, error) {
fBody, err := config.getNFunction()
if err != nil {
return "", err
}
return evalJavascript(fBody, encoded)
}
func evalJavascript(jsFunction, arg string) (string, error) {
const myName = "myFunction"
vm := goja.New()
_, err := vm.RunString(myName + "=" + jsFunction)
if err != nil {
return "", err
}
var output func(string) string
err = vm.ExportTo(vm.Get(myName), &output)
if err != nil {
return "", err
}
return output(arg), nil
}
func (config playerConfig) getNFunction() (string, error) {
nameResult := nFunctionNameRegexp.FindSubmatch(config)
if len(nameResult) == 0 {
return "", errors.New("unable to extract n-function name")
}
var name string
if idx, _ := strconv.Atoi(string(nameResult[2])); idx == 0 {
name = string(nameResult[4])
} else {
name = string(nameResult[1])
}
return config.extraFunction(name)
}
func (config playerConfig) extraFunction(name string) (string, error) {
// find the beginning of the function
def := []byte(name + "=function(")
start := bytes.Index(config, def)
if start < 1 {
return "", fmt.Errorf("unable to extract n-function body: looking for '%s'", def)
}
// start after the first curly bracket
pos := start + bytes.IndexByte(config[start:], '{') + 1
var strChar byte
// find the bracket closing the function
for brackets := 1; brackets > 0; pos++ {
b := config[pos]
switch b {
case '{':
if strChar == 0 {
brackets++
}
case '}':
if strChar == 0 {
brackets--
}
case '`', '"', '\'':
if config[pos-1] == '\\' && config[pos-2] != '\\' {
continue
}
if strChar == 0 {
strChar = b
} else if strChar == b {
strChar = 0
}
}
}
return string(config[start:pos]), nil
}
func (config playerConfig) decrypt(cyphertext []byte) ([]byte, error) {
operations, err := config.parseDecipherOps()
if err != nil {
return nil, err
}
// apply operations
bs := []byte(cyphertext)
for _, op := range operations {
bs = op(bs)
}
return bs, nil
}
/*
parses decipher operations from https://youtube.com/s/player/4fbb4d5b/player_ias.vflset/en_US/base.js
var Mt={
splice:function(a,b){a.splice(0,b)},
reverse:function(a){a.reverse()},
EQ:function(a,b){var c=a[0];a[0]=a[b%a.length];a[b%a.length]=c}};
a=a.split("");
Mt.splice(a,3);
Mt.EQ(a,39);
Mt.splice(a,2);
Mt.EQ(a,1);
Mt.splice(a,1);
Mt.EQ(a,35);
Mt.EQ(a,51);
Mt.splice(a,2);
Mt.reverse(a,52);
return a.join("")
*/
func (config playerConfig) parseDecipherOps() (operations []DecipherOperation, err error) {
objResult := actionsObjRegexp.FindSubmatch(config)
funcResult := actionsFuncRegexp.FindSubmatch(config)
if len(objResult) < 3 || len(funcResult) < 2 {
return nil, fmt.Errorf("error parsing signature tokens (#obj=%d, #func=%d)", len(objResult), len(funcResult))
}
obj := objResult[1]
objBody := objResult[2]
funcBody := funcResult[1]
var reverseKey, spliceKey, swapKey string
if result := reverseRegexp.FindSubmatch(objBody); len(result) > 1 {
reverseKey = string(result[1])
}
if result := spliceRegexp.FindSubmatch(objBody); len(result) > 1 {
spliceKey = string(result[1])
}
if result := swapRegexp.FindSubmatch(objBody); len(result) > 1 {
swapKey = string(result[1])
}
regex, err := regexp.Compile(fmt.Sprintf("(?:a=)?%s\\.(%s|%s|%s)\\(a,(\\d+)\\)", regexp.QuoteMeta(string(obj)), regexp.QuoteMeta(reverseKey), regexp.QuoteMeta(spliceKey), regexp.QuoteMeta(swapKey)))
if err != nil {
return nil, err
}
var ops []DecipherOperation
for _, s := range regex.FindAllSubmatch(funcBody, -1) {
switch string(s[1]) {
case reverseKey:
ops = append(ops, reverseFunc)
case swapKey:
arg, _ := strconv.Atoi(string(s[2]))
ops = append(ops, newSwapFunc(arg))
case spliceKey:
arg, _ := strconv.Atoi(string(s[2]))
ops = append(ops, newSpliceFunc(arg))
}
}
return ops, nil
}