castle-web-cli 0.4.141 → 0.4.144

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,193 @@
1
+ import { createHmac, randomBytes, timingSafeEqual } from 'crypto';
2
+ const CROCKFORD = '0123456789abcdefghjkmnpqrstvwxyz';
3
+ const CONTENT_LABEL_RE = /^1([ep])([0-9a-z]{1,4})-([a-z0-9]{14})-([0-9a-z]{1,8})-([0-9a-hjkmnp-tv-z]{13})-([0-9a-hjkmnp-tv-z]{20})$/;
4
+ const MAX_GRANT_SECONDS = 12 * 60 * 60;
5
+ const GRANT_CLOCK_SKEW_SECONDS = 60;
6
+ function base32Lower(bytes) {
7
+ let bits = 0;
8
+ let value = 0;
9
+ let out = '';
10
+ for (const byte of bytes) {
11
+ value = (value << 8) | byte;
12
+ bits += 8;
13
+ while (bits >= 5) {
14
+ out += CROCKFORD[(value >>> (bits - 5)) & 31];
15
+ bits -= 5;
16
+ }
17
+ }
18
+ if (bits > 0)
19
+ out += CROCKFORD[(value << (5 - bits)) & 31];
20
+ return out;
21
+ }
22
+ function safeEqual(a, b) {
23
+ const aa = Buffer.from(a);
24
+ const bb = Buffer.from(b);
25
+ return aa.length === bb.length && timingSafeEqual(aa, bb);
26
+ }
27
+ function hostWithoutPort(host) {
28
+ if (host.startsWith('['))
29
+ return host.slice(0, host.indexOf(']') + 1).toLowerCase();
30
+ return host.split(':')[0].toLowerCase();
31
+ }
32
+ function requestOrigin(req) {
33
+ const forwarded = req.headers['x-forwarded-proto'];
34
+ const protocol = typeof forwarded === 'string' ? forwarded.split(',')[0] : 'http';
35
+ return `${protocol}://${req.headers.host}`;
36
+ }
37
+ export function mintContentGrantLabel(grant, signingKey) {
38
+ const input = [
39
+ 'castle-content-v1',
40
+ grant.role,
41
+ String(grant.publicPort),
42
+ grant.sandboxId,
43
+ String(grant.expiresAtSeconds),
44
+ grant.serveNonce,
45
+ ].join('\n');
46
+ const mac = base32Lower(createHmac('sha256', signingKey).update(input).digest().subarray(0, 12));
47
+ const roleCode = grant.role === 'edit' ? 'e' : 'p';
48
+ return `1${roleCode}${grant.publicPort.toString(36)}-${grant.sandboxId}-${grant.expiresAtSeconds.toString(36)}-${grant.serveNonce}-${mac}`;
49
+ }
50
+ export class ServeSecurity {
51
+ publicPort;
52
+ serveToken = randomBytes(32).toString('base64url');
53
+ signingKey = process.env.CASTLE_AGENT_TOKEN || randomBytes(32).toString('base64url');
54
+ serveNonce = base32Lower(randomBytes(8));
55
+ tickets = new Map();
56
+ constructor(publicPort) {
57
+ this.publicPort = publicPort;
58
+ }
59
+ authorizeHttp(req) {
60
+ const value = req.headers['x-castle-serve-token'];
61
+ return typeof value === 'string' && safeEqual(value, this.serveToken);
62
+ }
63
+ issueTicket(endpoint) {
64
+ this.pruneTickets();
65
+ const ticket = randomBytes(16).toString('base64url');
66
+ this.tickets.set(ticket, { endpoint, expiresAt: Date.now() + 30_000 });
67
+ return ticket;
68
+ }
69
+ consumeTicket(req, endpoint) {
70
+ this.pruneTickets();
71
+ let ticket = '';
72
+ try {
73
+ ticket = new URL(req.url || '/', 'http://localhost').searchParams.get('ticket') || '';
74
+ }
75
+ catch {
76
+ return false;
77
+ }
78
+ const record = this.tickets.get(ticket);
79
+ if (!record)
80
+ return false;
81
+ this.tickets.delete(ticket);
82
+ return record.endpoint === endpoint && record.expiresAt > Date.now();
83
+ }
84
+ pruneTickets() {
85
+ const now = Date.now();
86
+ for (const [ticket, record] of this.tickets) {
87
+ if (record.expiresAt <= now)
88
+ this.tickets.delete(ticket);
89
+ }
90
+ }
91
+ shellBootstrap(req) {
92
+ const { editOrigin, playOrigin } = this.contentOrigins(req);
93
+ let hostOrigin = null;
94
+ try {
95
+ const referrer = typeof req.headers.referer === 'string' ? new URL(req.headers.referer) : null;
96
+ hostOrigin =
97
+ referrer &&
98
+ referrer.protocol === 'https:' &&
99
+ (referrer.hostname === 'castle.xyz' || referrer.hostname.endsWith('.castle.xyz'))
100
+ ? referrer.origin
101
+ : null;
102
+ }
103
+ catch {
104
+ /* absent or malformed referrer */
105
+ }
106
+ if (!hostOrigin &&
107
+ /\.sandboxes(?:-staging)?\.castle\.xyz(?::\d+)?$/i.test(req.headers.host || '')) {
108
+ hostOrigin = 'https://castle.xyz';
109
+ }
110
+ return `<script>(function(){
111
+ window.__CASTLE_SERVE_TOKEN__=${JSON.stringify(this.serveToken)};
112
+ window.__CASTLE_CONTENT_ORIGINS__=${JSON.stringify({ edit: editOrigin, play: playOrigin })};
113
+ window.__CASTLE_HOST_ORIGIN__=${JSON.stringify(hostOrigin)};
114
+ var nativeFetch=window.fetch.bind(window);
115
+ window.fetch=function(input,init){
116
+ try {
117
+ var u=new URL(typeof input==='string'?input:input.url,location.href);
118
+ if(u.origin===location.origin&&u.pathname.indexOf('/__castle/')===0){
119
+ init=Object.assign({},init||{});
120
+ var h=new Headers(init.headers||(typeof input!=='string'&&input.headers)||undefined);
121
+ h.set('X-Castle-Serve-Token',window.__CASTLE_SERVE_TOKEN__);
122
+ init.headers=h;
123
+ }
124
+ }catch(e){}
125
+ return nativeFetch(input,init);
126
+ };
127
+ })();</script>`;
128
+ }
129
+ contentOrigins(req) {
130
+ const host = hostWithoutPort(req.headers.host || 'localhost');
131
+ const cloud = host.match(/^\d+-([a-z0-9]{14})\.(sandboxes(?:-staging)?\.castle\.xyz)$/);
132
+ const sandboxId = cloud?.[1] || 'localdev000000';
133
+ const contentHeader = req.headers['x-castle-content-domain'];
134
+ const contentDomain = typeof contentHeader === 'string' &&
135
+ /^(?:sandboxes|sandboxes-staging)\.castlexyz\.com$/.test(contentHeader)
136
+ ? contentHeader.toLowerCase()
137
+ : cloud?.[2] === 'sandboxes-staging.castle.xyz'
138
+ ? 'sandboxes-staging.castlexyz.com'
139
+ : cloud
140
+ ? 'sandboxes.castlexyz.com'
141
+ : 'localhost';
142
+ // Leave room for small positive clock skew at the control plane. Ghost still
143
+ // enforces the hard 12-hour maximum when it resolves the capability.
144
+ const expiresAtSeconds = Math.floor(Date.now() / 1000) + MAX_GRANT_SECONDS - GRANT_CLOCK_SKEW_SECONDS;
145
+ const originFor = (role) => {
146
+ const label = this.mintContentLabel(role, sandboxId, expiresAtSeconds);
147
+ return cloud
148
+ ? `https://${label}.${contentDomain}`
149
+ : `${requestOrigin(req).split('://')[0]}://${label}.localhost:${this.publicPort}`;
150
+ };
151
+ return { editOrigin: originFor('edit'), playOrigin: originFor('play') };
152
+ }
153
+ localContentOrigin(role) {
154
+ const expiresAtSeconds = Math.floor(Date.now() / 1000) + MAX_GRANT_SECONDS - GRANT_CLOCK_SKEW_SECONDS;
155
+ const label = this.mintContentLabel(role, 'localdev000000', expiresAtSeconds);
156
+ return `http://${label}.localhost:${this.publicPort}`;
157
+ }
158
+ verifyContentRequest(req) {
159
+ const host = hostWithoutPort(req.headers.host || '');
160
+ const label = host.split('.')[0];
161
+ const match = CONTENT_LABEL_RE.exec(label);
162
+ if (!match)
163
+ return null;
164
+ const publicPort = Number.parseInt(match[2], 36);
165
+ const expiresAtSeconds = Number.parseInt(match[4], 36);
166
+ const role = match[1] === 'e' ? 'edit' : 'play';
167
+ if (publicPort !== this.publicPort ||
168
+ expiresAtSeconds <= Math.floor(Date.now() / 1000) ||
169
+ expiresAtSeconds > Math.floor(Date.now() / 1000) + MAX_GRANT_SECONDS ||
170
+ match[5] !== this.serveNonce) {
171
+ return null;
172
+ }
173
+ const expected = this.contentMac(role, publicPort, match[3], expiresAtSeconds, match[5]);
174
+ return safeEqual(expected, match[6]) ? role : null;
175
+ }
176
+ shellOrigin(req) {
177
+ return requestOrigin(req);
178
+ }
179
+ mintContentLabel(role, sandboxId, expiresAtSeconds) {
180
+ return mintContentGrantLabel({
181
+ role,
182
+ publicPort: this.publicPort,
183
+ sandboxId,
184
+ expiresAtSeconds,
185
+ serveNonce: this.serveNonce,
186
+ }, this.signingKey);
187
+ }
188
+ contentMac(role, publicPort, sandboxId, expiresAtSeconds, serveNonce) {
189
+ return mintContentGrantLabel({ role, publicPort, sandboxId, expiresAtSeconds, serveNonce }, this.signingKey)
190
+ .split('-')
191
+ .at(-1);
192
+ }
193
+ }