-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
227 lines (187 loc) · 6.32 KB
/
server.js
File metadata and controls
227 lines (187 loc) · 6.32 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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
"use strict";
// Load environment variables
require('dotenv').config({ path: '../../../.env' });
const session = require('cookie-session');
const ejs = require('ejs');
const express = require('express');
const crypto = require('crypto');
const nocache = require('nocache');
const app = express();
const port = process.env.PORT || 3034;
let uidBaseUrl = process.env.UID_SERVER_BASE_URL;
const subscriptionId = process.env.UID_CSTG_SUBSCRIPTION_ID;
const serverPublicKey = process.env.UID_CSTG_SERVER_PUBLIC_KEY;
const identityName = process.env.IDENTITY_NAME;
const docsBaseUrl = process.env.DOCS_BASE_URL;
// additional packages/variables needed to ensure compabitibility with the SDK
const { JSDOM } = require('jsdom'); // for simulating a browser environment
const util = require('util'); // for polyfilling TextEncoder and TextDecoder
const XMLHttpRequest = require('xhr2'); // for making HTTP requests
const clientOrigin = process.env.UID_CSTG_ORIGIN || `http://localhost:${port}`; // Client origin: the URL where this app is accessible
// Create a virtual DOM environment for the SDK to run in
let SdkClass = null;
let uidSdk = null;
let dom = null;
async function initializeSDK() {
dom = new JSDOM('<!DOCTYPE html><html><body></body></html>', {
url: clientOrigin,
runScripts: 'dangerously',
resources: 'usable',
pretendToBeVisual: true,
});
// Polyfills for Browser APIs, SDK uses them extensively (e.g., for token storage or making network requests
global.window = dom.window;
global.document = dom.window.document;
global.navigator = dom.window.navigator;
global.localStorage = dom.window.localStorage;
// Polyfill Web Crypto API for jsdom (SDK uses crypto.subtle for AES-GCM encryption/decryption)
Object.defineProperty(dom.window, 'crypto', {
value: crypto.webcrypto,
writable: false,
configurable: true
});
// Polyfill TextEncoder and TextDecoder (required by SDK for string/byte conversion)
global.TextEncoder = util.TextEncoder;
global.TextDecoder = util.TextDecoder;
dom.window.TextEncoder = util.TextEncoder;
dom.window.TextDecoder = util.TextDecoder;
// Polyfill XMLHttpRequest with Origin header support
const OriginalXHR = XMLHttpRequest;
class XMLHttpRequestWithOrigin extends OriginalXHR {
constructor() {
super();
this._origin = clientOrigin;
this._customHeaders = {};
}
open(method, url, async) {
const result = super.open(method, url, async);
return result;
}
setRequestHeader(header, value) {
// Allow 'Origin' header that xhr2 normally blocks
this._customHeaders[header] = value;
if (header.toLowerCase() !== 'origin') {
return super.setRequestHeader(header, value);
}
}
send(body) {
if (!this._headers) {
this._headers = {};
}
this._headers.origin = this._origin;
return super.send(body);
}
}
global.XMLHttpRequest = XMLHttpRequestWithOrigin;
dom.window.XMLHttpRequest = XMLHttpRequestWithOrigin;
try {
const isEUID = identityName && identityName.toUpperCase() === 'EUID';
if (isEUID) {
const { EUID } = await import('@unified-id/euid-sdk');
SdkClass = EUID;
} else {
const { UID2 } = await import('@uid2/uid2-sdk');
SdkClass = UID2;
}
// Instantiate the SDK (UID2 or EUID based on config) with base URL
uidSdk = new SdkClass();
uidSdk.init({ baseUrl: uidBaseUrl });
return uidSdk;
} catch (error) {
console.error('Failed to initialize SDK:', error);
throw error;
}
}
// Express middleware setup
app.use(session({
keys: [process.env.SESSION_KEY || 'default-session-key-change-me'],
maxAge: 24 * 60 * 60 * 1000 // 24 hours
}));
app.use(express.static('public'));
app.use(express.urlencoded({ extended: true }));
app.engine('.html', ejs.__express);
app.set('view engine', 'html');
app.use(nocache());
// Routes
app.get('/', (req, res) => {
res.render('index', {
identity: req.session.identity || null,
identityName,
docsBaseUrl
});
});
/**
* Handle login form submission
* Uses the JavaScript SDK's setIdentityFromEmail method on the server
*/
app.post('/login', async (req, res) => {
if (!uidSdk) {
return res.render('error', {
error: 'SDK not initialized. Server may still be starting up.',
response: null,
identityName,
docsBaseUrl
});
}
try {
// Call the SDK's setIdentityFromEmail method and wait for the result via callback
const identity = await new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error('Token generation timed out after 10 seconds'));
}, 10000);
const callbackHandler = (eventType, payload) => {
if ((eventType === 'InitCompleted' || eventType === 'IdentityUpdated') && payload?.identity) {
clearTimeout(timeout);
uidSdk.callbacks.splice(uidSdk.callbacks.indexOf(callbackHandler), 1);
resolve(payload.identity);
}
if (eventType === 'OptoutReceived') {
clearTimeout(timeout);
uidSdk.callbacks.splice(uidSdk.callbacks.indexOf(callbackHandler), 1);
reject(new Error('Got unexpected token generate status: optout'));
}
};
uidSdk.callbacks.push(callbackHandler);
uidSdk.setIdentityFromEmail(
req.body.email,
{
subscriptionId: subscriptionId,
serverPublicKey: serverPublicKey
}
).catch(err => {
clearTimeout(timeout);
reject(err);
});
});
if (!identity) {
throw new Error('No identity returned from SDK');
}
req.session.identity = identity;
res.redirect('/');
} catch (error) {
console.error('Token generation failed:', error.message);
req.session = null;
res.render('error', {
error: error.message || error.toString(),
response: error.response || null,
identityName,
docsBaseUrl
});
}
});
app.get('/logout', (req, res) => {
if (uidSdk && uidSdk.disconnect) {
uidSdk.disconnect();
}
req.session = null;
res.redirect('/');
});
// Start server and initialize SDK
initializeSDK().then(() => {
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
}).catch(error => {
console.error('Failed to start server:', error);
process.exit(1);
});