Repository navigation
Expand file tree
/
Copy pathprocessor.go
More file actions
204 lines (177 loc) · 4.96 KB
/
Copy pathprocessor.go
File metadata and controls
204 lines (177 loc) · 4.96 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
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
package pana
import (
"bytes"
"context"
"encoding/json/jsontext"
"fmt"
"io"
"log/slog"
"slices"
"strings"
ld "sourcery.dny.nu/longdistance"
"sourcery.dny.nu/pana/internal/jsonutil"
"sourcery.dny.nu/pana/internal/loader"
as "sourcery.dny.nu/pana/vocab/w3/activitystreams"
secv1 "sourcery.dny.nu/pana/vocab/w3id/securityv1"
)
// Processor is used to process incoming messages and prepare outgoing messages.
//
// Your application only needs a single processor instance.
type Processor struct {
ldproc *ld.Processor
}
// New initialised a new [Processor] suitable for dealing with
// ActivityStreams messages.
//
// It uses [loader.Builtin] to retrieve contexts and does not retrieve them over
// the network. It also uses [ValidateContext] to enforce additional constraints
// on the context term definitions.
func New(
logger *slog.Logger,
) *Processor {
if logger == nil {
logger = slog.New(slog.DiscardHandler)
}
opts := []ld.ProcessorOption{
ld.WithLogger(logger),
ld.WithCompactArrays(true),
ld.WithCompactToRelative(false),
ld.With10Processing(false), // Misskey seems to do some JSON-LD 1.1
ld.WithRemoteContextLoader((loader.New()).Get),
ld.WithExcludeIRIsFromCompaction(as.PublicCollection),
ld.WithValidateContext(ValidateContext),
ld.WithDisallowedKeywords(
ld.KeywordIncluded, ld.KeywordIndex,
ld.KeywordGraph, ld.KeywordNest,
ld.KeywordReverse),
}
for iri, ctx := range cacheableContexts() {
opts = append(opts, ld.WithProcessedContext(iri, ctx))
}
return &Processor{ldproc: ld.NewProcessor(opts...)}
}
// Marshal takes any of the types in this package and returns JSON-LD in
// compacted document form.
//
// This is the shape of JSON you want to exchange with other servers and
// clients.
//
// The compaction context is a JSON document representing the JSON-LD context
// that should be used for compaction. If the compaction context is not
// provided, [Divinate] will be used to attempt and determine an appropriate
// one.
func (p *Processor) Marshal[T node](
ctx context.Context,
dst io.Writer,
compactionContext jsontext.Value,
object T,
) error {
if compactionContext == nil {
res, err := Divinate(ld.Node(object))
if err != nil {
return fmt.Errorf("context divination failed: %w", err)
}
compactionContext = res
}
if compactionContext[0] == '{' {
ctx, err := jsonutil.GetContextDocument(compactionContext)
if err != nil {
return err
}
compactionContext = ctx
}
return p.ldproc.Compact(
ctx,
dst,
compactionContext,
[]ld.Node{ld.Node(object)},
"",
)
}
// Unmarshal takes a JSON document and returns an [Any] that represents it
// using JSON-LD expanded document form.
//
// If the document was retrieved over HTTP, the request URL should be passed
// as the second argument.
//
// In JSON-LD the result of expanding a document is always a list. But in the
// case of ActivityPub we only ever send out a single document at a time, so it
// returns [Any]. If the result happens to have more than one object an error is
// raised so it doesn't go unnoticed.
func (p *Processor) Unmarshal(
ctx context.Context,
document io.Reader,
url string,
) (*Any, error) {
res, err := p.ldproc.Expand(ctx, document, url)
if err != nil {
return nil, err
}
if lres := len(res); lres != 1 {
return nil, fmt.Errorf("expected a single document, got: %d", lres)
}
return (*Any)(&res[0]), nil
}
// ValidateContext enforces that the term to IRI mapping for certain contexts
// match their normative context definition. This ensures IRIs aren't compacted
// to unexpected terms.
func ValidateContext(ctx *ld.Context) bool {
for term, def := range ctx.Terms() {
if strings.HasPrefix(def.IRI, as.Namespace) {
if def.Prefix {
if term == "as" && def.IRI != as.Namespace {
return false
}
continue
}
short := as.Term(def.IRI)
if slices.Equal(def.Container, []string{ld.KeywordLanguage}) {
if term != short && term != short+"Map" {
return false
}
continue
}
if slices.Equal(def.Container, []string{ld.KeywordList}) {
if term != short && term != "ordered"+strings.ToUpper(short[:1])+short[1:] {
return false
}
continue
}
if term != as.Term(def.IRI) {
return false
}
continue
}
if strings.HasPrefix(def.IRI, secv1.Namespace) {
if def.Prefix {
if term == "sec" && def.IRI != secv1.Namespace {
return false
}
continue
}
// expires is an alias for expiration.
if term == "expires" && def.IRI == secv1.Expiration {
continue
}
if term != secv1.Term(def.IRI) {
return false
}
}
}
return true
}
func cacheableContexts() map[string]*ld.Context {
elems := map[string][]byte{
as.IRI: as.ContextDocument,
secv1.IRI: secv1.ContextDocument,
}
res := make(map[string]*ld.Context, len(elems))
p := ld.NewProcessor(
ld.With10Processing(false),
)
for iri, doc := range elems {
ctx, _ := jsonutil.GetContextDocument(doc)
res[iri] = p.CacheableContext(context.Background(), iri, bytes.NewBuffer(ctx))
}
return res
}