oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package provider
2
3import (
4 "bytes"
5 "encoding/json"
6 "io"
7)
8
9type nativeEnvelope struct {
10 ID json.RawMessage `json:"id"`
11 Method string `json:"method"`
12 Params json.RawMessage `json:"params"`
13 Result json.RawMessage `json:"result"`
14 Error json.RawMessage `json:"error"`
15}
16
17func parseNative(raw []byte) (nativeEnvelope, error) {
18 var v nativeEnvelope
19 if len(raw) == 0 || len(raw) > (1<<20) || !uniqueNativeJSON(raw) || json.Unmarshal(raw, &v) != nil {
20 return v, ErrPolicy
21 }
22 if len(v.ID) > 0 {
23 var s string
24 var n int64
25 if json.Unmarshal(v.ID, &s) != nil && json.Unmarshal(v.ID, &n) != nil {
26 return v, ErrPolicy
27 }
28 if bytes.Equal(v.ID, []byte("null")) {
29 return v, ErrPolicy
30 }
31 }
32 if v.Method != "" {
33 if len(v.Result) > 0 || len(v.Error) > 0 || len(v.Params) == 0 {
34 return v, ErrPolicy
35 }
36 } else if len(v.ID) == 0 || (len(v.Result) == 0) == (len(v.Error) == 0) {
37 return v, ErrPolicy
38 }
39 return v, nil
40}
41
42func uniqueNativeJSON(raw []byte) bool {
43 d := json.NewDecoder(bytes.NewReader(raw))
44 d.UseNumber()
45 var value func() bool
46 value = func() bool {
47 token, e := d.Token()
48 if e != nil {
49 return false
50 }
51 delim, ok := token.(json.Delim)
52 if !ok {
53 return true
54 }
55 switch delim {
56 case '{':
57 seen := map[string]bool{}
58 for d.More() {
59 k, e := d.Token()
60 if e != nil {
61 return false
62 }
63 s, ok := k.(string)
64 if !ok || seen[s] {
65 return false
66 }
67 seen[s] = true
68 if !value() {
69 return false
70 }
71 }
72 end, e := d.Token()
73 return e == nil && end == json.Delim('}')
74 case '[':
75 for d.More() {
76 if !value() {
77 return false
78 }
79 }
80 end, e := d.Token()
81 return e == nil && end == json.Delim(']')
82 }
83 return false
84 }
85 if !value() {
86 return false
87 }
88 _, e := d.Token()
89 return e == io.EOF
90}
91