-
Notifications
You must be signed in to change notification settings - Fork 28
/
index.js
333 lines (286 loc) · 9.69 KB
/
index.js
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
/*
Copyright 2022 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// SSP
import express from "express"
import url from "url"
import cbor from "cbor"
import { decodeDict } from "structured-field-values"
import {
debugKey,
sourceEventId,
sourceKeyPiece,
triggerKeyPiece,
ADVERTISER,
PUBLISHER,
DIMENSION,
decodeBucket,
SOURCE_TYPE,
TRIGGER_TYPE
} from "./arapi.js"
const { EXTERNAL_PORT, PORT, SSP_HOST, SSP_DETAIL, SSP_TOKEN, DSP_HOST, SHOP_HOST } = process.env
// global memory storage
const Reports = []
// clear storage
setInterval(() => {
Reports.length = 0
}, 1000 * 60 * 10)
const app = express()
app.use((req, res, next) => {
res.setHeader("Origin-Trial", SSP_TOKEN)
next()
})
app.use(express.json())
app.use((req, res, next) => {
// enable debug mode
res.cookie("ar_debug", "1", {
sameSite: "none",
secure: true,
httpOnly: true
})
next()
})
app.use((req, res, next) => {
// opt-in fencedframe
if (req.get("sec-fetch-dest") === "fencedframe") {
res.setHeader("Supports-Loading-Mode", "fenced-frame")
}
next()
})
app.use(
express.static("src/public", {
setHeaders: (res, path, stat) => {
if (path.endsWith("/decision-logic.js")) {
return res.set("X-Allow-FLEDGE", "true")
}
if (path.endsWith("/run-ad-auction.js")) {
res.set("Supports-Loading-Mode", "fenced-frame")
res.set("Permissions-Policy", "run-ad-auction=(*)")
}
}
})
)
app.set("view engine", "ejs")
app.set("views", "src/views")
app.get("/", async (req, res) => {
const title = SSP_DETAIL
res.render("index.html.ejs", { title, SSP_HOST, EXTERNAL_PORT, SHOP_HOST })
})
app.get("/ads", async (req, res) => {
const { advertiser, id } = req.query
console.log("Loading frame content : ", { advertiser, id })
const title = `Your special ads from ${advertiser}`
const move = new URL(`https://${SSP_HOST}:${EXTERNAL_PORT}/move`)
move.searchParams.append("advertiser", advertiser)
move.searchParams.append("id", id)
const creative = new URL(`https://${SSP_HOST}:${EXTERNAL_PORT}/creative`)
creative.searchParams.append("advertiser", advertiser)
creative.searchParams.append("id", id)
const registerSource = new URL(`https://${SSP_HOST}:${EXTERNAL_PORT}/register-source`)
registerSource.searchParams.append("advertiser", advertiser)
registerSource.searchParams.append("id", id)
res.render("ads.html.ejs", { title, move, creative, registerSource })
})
app.get("/register-source", async (req, res) => {
const { advertiser, id } = req.query
console.log("Registering source attribution for", { advertiser, id })
if (req.headers["attribution-reporting-eligible"]) {
//const are = req.headers["attribution-reporting-eligible"].split(",").map((e) => e.trim())
const are = decodeDict(req.headers["attribution-reporting-eligible"])
// register navigation source
if ("navigation-source" in are) {
const destination = `https://${advertiser}`
const source_event_id = sourceEventId()
const debug_key = debugKey()
const AttributionReportingRegisterSource = {
destination,
source_event_id,
debug_key,
aggregation_keys: {
quantity: sourceKeyPiece({
type: SOURCE_TYPE["click"], // click attribution
advertiser: ADVERTISER[advertiser],
publisher: PUBLISHER["news"],
id: Number(`0x${id}`),
dimension: DIMENSION["quantity"]
}),
gross: sourceKeyPiece({
type: SOURCE_TYPE["click"], // click attribution
advertiser: ADVERTISER[advertiser],
publisher: PUBLISHER["news"],
id: Number(`0x${id}`),
dimension: DIMENSION["gross"]
})
}
}
console.log("Registering navigation source :", { AttributionReportingRegisterSource })
res.setHeader("Attribution-Reporting-Register-Source", JSON.stringify(AttributionReportingRegisterSource))
res.status(200).send("attribution nevigation (click) source registered")
}
// register event source
else if ("event-source" in are) {
const destination = `https://${advertiser}`
const source_event_id = sourceEventId()
const debug_key = debugKey()
const AttributionReportingRegisterSource = {
destination,
source_event_id,
debug_key,
aggregation_keys: {
quantity: sourceKeyPiece({
type: SOURCE_TYPE["view"], // view attribution
advertiser: ADVERTISER[advertiser],
publisher: PUBLISHER["news"],
id: Number(`0x${id}`),
dimension: DIMENSION["quantity"]
}),
gross: sourceKeyPiece({
type: SOURCE_TYPE["view"], // view attribution
advertiser: ADVERTISER[advertiser],
publisher: PUBLISHER["news"],
id: Number(`0x${id}`),
dimension: DIMENSION["gross"]
})
}
}
console.log("Registering event source :", { AttributionReportingRegisterSource })
res.setHeader("Attribution-Reporting-Register-Source", JSON.stringify(AttributionReportingRegisterSource))
res.status(200).send("attribution event (view) source registered")
} else {
res.status(400).send("'Attribution-Reporting-Eligible' header is malformed") // just send back response header. no content.
}
} else {
res.status(400).send("'Attribution-Reporting-Eligible' header is missing") // just send back response header. no content.
}
})
app.get("/move", async (req, res) => {
const { advertiser, id } = req.query
//console.log({ advertiser, id })
const url = `https://${advertiser}/items/${id}`
res.redirect(302, url)
})
app.get("/creative", async (req, res) => {
const { advertiser, id } = req.query
// redirect to advertisers Ads endpoint
res.redirect(`https://${advertiser}/ads/${id}`)
})
app.get("/register-trigger", async (req, res) => {
const { id, quantity, size, category, gross } = req.query
const AttributionReportingRegisterTrigger = {
aggregatable_trigger_data: [
{
key_piece: triggerKeyPiece({
type: TRIGGER_TYPE["quantity"],
id: parseInt(id, 16),
size: Number(size),
category: Number(category),
option: 0
}),
source_keys: ["quantity"]
},
{
key_piece: triggerKeyPiece({
type: TRIGGER_TYPE["gross"],
id: parseInt(id, 16),
size: Number(size),
category: Number(category),
option: 0
}),
source_keys: ["gross"]
}
],
aggregatable_values: {
// TODO: scaling
quantity: Number(quantity),
gross: Number(gross)
},
debug_key: debugKey()
}
res.setHeader("Attribution-Reporting-Register-Trigger", JSON.stringify(AttributionReportingRegisterTrigger))
res.sendStatus(200)
})
app.get("/ad-tag.html", async (req, res) => {
res.render("ad-tag.html.ejs")
})
app.get("/video-ad-tag.html", async (req, res) => {
res.render("video-ad-tag.html.ejs")
})
app.get("/reports", async (req, res) => {
res.render("reports.html.ejs", { title: "Report", Reports })
})
app.get("/auction-config.json", async (req, res) => {
const DSP = new URL(`https://${DSP_HOST}:${EXTERNAL_PORT}`)
const SSP = new URL(`https://${SSP_HOST}:${EXTERNAL_PORT}`)
const auctionConfig = {
// should https & same as decisionLogicUrl's origin
seller: SSP,
// x-allow-fledge: true
decisionLogicUrl: `${SSP}js/decision-logic.js`,
interestGroupBuyers: [
// * is not supported yet
DSP
],
// public for everyone
auctionSignals: {
auction_signals: "auction_signals"
},
// only for single party
sellerSignals: {
seller_signals: "seller_signals"
},
// only for single party
perBuyerSignals: {
// listed on interestGroupByers
[DSP]: {
per_buyer_signals: "per_buyer_signals"
}
},
// use with fencedframe
resolveToConfig: true
}
console.log({ auctionConfig })
res.json(auctionConfig)
})
app.post("/.well-known/attribution-reporting/debug/report-aggregate-attribution", async (req, res) => {
const debug_report = req.body
debug_report.shared_info = JSON.parse(debug_report.shared_info)
console.log(JSON.stringify(debug_report, " ", " "))
debug_report.aggregation_service_payloads = debug_report.aggregation_service_payloads.map((e) => {
const plain = Buffer.from(e.debug_cleartext_payload, "base64")
const debug_cleartext_payload = cbor.decodeAllSync(plain)
e.debug_cleartext_payload = debug_cleartext_payload.map(({ data, operation }) => {
return {
operation,
data: data.map(({ value, bucket }) => {
return {
value: value.readUInt32BE(0),
bucket: decodeBucket(bucket)
}
})
}
})
return e
})
console.log(JSON.stringify(debug_report, " ", " "))
// save to global storage
Reports.push(debug_report)
res.sendStatus(200)
})
app.post("/.well-known/attribution-reporting/report-aggregate-attribution", async (req, res) => {
const report = req.body
report.shared_info = JSON.parse(report.shared_info)
console.log(JSON.stringify(report, " ", " "))
res.sendStatus(200)
})
app.listen(PORT, function () {
console.log(`Listening on port ${PORT}`)
})