@bstage-sdk/bridge 0.14.2 → 0.15.0

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.
package/dist/host.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import {
2
+ ACCOUNT_SESSION_CAPABILITY,
2
3
  ALLOWED_METHODS,
3
4
  ALLOWED_REQUEST_HEADERS,
4
5
  BRIDGE_SURFACES,
@@ -10,9 +11,11 @@ import {
10
11
  HOST_ONLY_HEADERS,
11
12
  IFRAME_ATTRIBUTES,
12
13
  INIT_RESPONSE,
14
+ KNOWN_CAPABILITIES,
13
15
  MAX_DECODE_PASSES,
14
16
  MAX_PARTNER_ORIGINS,
15
17
  MAX_PASS_THROUGH_HEADERS,
18
+ OTP_OPS,
16
19
  READY_EVENT,
17
20
  REPORTS_PER_SESSION,
18
21
  REPORT_COUNT_MAX,
@@ -21,6 +24,7 @@ import {
21
24
  REPORT_MESSAGE_MAX_LENGTH,
22
25
  ROUTING_HEADERS,
23
26
  ROUTING_HEADER_PREFIXES,
27
+ SESSION_OPS,
24
28
  TEMPLATE_REPORT_KINDS,
25
29
  checkPath,
26
30
  classifyDestination,
@@ -42,42 +46,522 @@ import {
42
46
  prepareFetch,
43
47
  resolveDestination,
44
48
  resolvePolicy
45
- } from "./chunk-5OWBSJ6E.js";
49
+ } from "./chunk-GWUVHC56.js";
46
50
  import "./chunk-TPKNGW34.js";
47
51
 
48
52
  // src/host/rateLimiter.ts
49
53
  var DEFAULT_WINDOW_MS = 6e4;
50
54
  function createRateLimiter(max, windowMs = DEFAULT_WINDOW_MS) {
51
- let stamps = [];
55
+ let stamps2 = [];
52
56
  return {
53
57
  take(now = Date.now()) {
54
- const recent = stamps.filter((t) => now - t < windowMs);
58
+ const recent = stamps2.filter((t) => now - t < windowMs);
55
59
  if (recent.length >= max) {
56
- stamps = recent;
60
+ stamps2 = recent;
57
61
  return false;
58
62
  }
59
- stamps = [...recent, now];
63
+ stamps2 = [...recent, now];
60
64
  return true;
61
65
  }
62
66
  };
63
67
  }
64
68
 
65
- // src/host/events.ts
69
+ // src/host/validators.ts
70
+ var MAX_PATH_LENGTH = 2048;
71
+ var TOAST_MAX_LENGTH = 500;
72
+ var TRACK_NAME_MAX_LENGTH = 100;
73
+ var TRACK_PARAMS_MAX_BYTES = 4096;
74
+ var RESIZE_MAX_HEIGHT = 2e5;
75
+ var LOG_MAX_LENGTH = 2e3;
76
+ var UNSAFE_KEYS = ["__proto__", "constructor", "prototype"];
77
+ var TOAST_KINDS = ["info", "success", "warning", "error"];
78
+ var LOG_LEVELS = ["debug", "info", "warn", "error"];
79
+ function field(payload, key) {
80
+ return typeof payload === "object" && payload !== null ? payload[key] : void 0;
81
+ }
82
+ function validatePath(payload, hostOrigin) {
83
+ const path = field(payload, "path");
84
+ if (typeof path !== "string" || path.length === 0 || path.length > MAX_PATH_LENGTH || !path.startsWith("/") || path.startsWith("//") || // eslint-disable-next-line no-control-regex -- 제어문자를 거르는 것이 목적이다
85
+ /[\s\\\u0000-\u001f\u007f]/.test(path)) {
86
+ throw new BridgeError("BAD_REQUEST", "invalid path");
87
+ }
88
+ let resolved;
89
+ try {
90
+ resolved = new URL(path, hostOrigin);
91
+ } catch {
92
+ throw new BridgeError("BAD_REQUEST", "invalid path");
93
+ }
94
+ if (resolved.origin !== new URL(hostOrigin).origin || resolved.pathname.startsWith("//")) {
95
+ throw new BridgeError("BAD_REQUEST", "invalid path");
96
+ }
97
+ if (!checkPath(resolved.pathname, { forbidDoubleSlash: true }).ok) {
98
+ throw new BridgeError("BAD_REQUEST", "invalid path");
99
+ }
100
+ return resolved.pathname + resolved.search + resolved.hash;
101
+ }
102
+ function validateNavigateOptions(payload) {
103
+ const replace = field(payload, "replace");
104
+ const reload = field(payload, "reload");
105
+ if (replace !== void 0 && typeof replace !== "boolean") {
106
+ throw new BridgeError("BAD_REQUEST", "invalid navigate options");
107
+ }
108
+ if (reload !== void 0 && typeof reload !== "boolean") {
109
+ throw new BridgeError("BAD_REQUEST", "invalid navigate options");
110
+ }
111
+ if (replace !== true && reload !== true) return void 0;
112
+ return { ...replace === true ? { replace } : {}, ...reload === true ? { reload } : {} };
113
+ }
114
+ function validateExternalUrl(payload) {
115
+ const raw = field(payload, "url");
116
+ if (typeof raw !== "string") throw new BridgeError("BAD_REQUEST", "invalid url");
117
+ let url;
118
+ try {
119
+ url = new URL(raw);
120
+ } catch {
121
+ throw new BridgeError("BAD_REQUEST", "invalid url");
122
+ }
123
+ if (url.protocol !== "https:" || url.username !== "" || url.password !== "") {
124
+ throw new BridgeError("FORBIDDEN_DESTINATION", "only https urls can be opened");
125
+ }
126
+ return url.href;
127
+ }
128
+ function validateToast(payload) {
129
+ const message = field(payload, "message");
130
+ if (typeof message !== "string") throw new BridgeError("BAD_REQUEST", "invalid toast");
131
+ const kind = field(payload, "kind");
132
+ const known = TOAST_KINDS.find((k) => k === kind);
133
+ return { message: message.slice(0, TOAST_MAX_LENGTH), ...known ? { kind: known } : {} };
134
+ }
135
+ function validateHeight(payload) {
136
+ const height = field(payload, "height");
137
+ if (typeof height !== "number" || !Number.isFinite(height)) {
138
+ throw new BridgeError("BAD_REQUEST", "invalid height");
139
+ }
140
+ return Math.min(RESIZE_MAX_HEIGHT, Math.max(0, Math.round(height)));
141
+ }
142
+ function validateTrack(payload) {
143
+ const name = field(payload, "name");
144
+ const params = field(payload, "params");
145
+ if (typeof name !== "string" || name.length === 0 || name.length > TRACK_NAME_MAX_LENGTH) {
146
+ throw new BridgeError("BAD_REQUEST", "invalid track name");
147
+ }
148
+ if (params === void 0) return { name };
149
+ if (typeof params !== "object" || params === null || Array.isArray(params)) {
150
+ throw new BridgeError("BAD_REQUEST", "invalid track params");
151
+ }
152
+ let serialized;
153
+ try {
154
+ serialized = JSON.stringify(params);
155
+ } catch {
156
+ throw new BridgeError("BAD_REQUEST", "invalid track params");
157
+ }
158
+ if (new TextEncoder().encode(serialized).length > TRACK_PARAMS_MAX_BYTES) {
159
+ throw new BridgeError("BAD_REQUEST", "track params too large");
160
+ }
161
+ return {
162
+ name,
163
+ params: JSON.parse(
164
+ serialized,
165
+ (key, value) => UNSAFE_KEYS.includes(key) ? void 0 : value
166
+ )
167
+ };
168
+ }
169
+ function validateLog(payload) {
170
+ const level = field(payload, "level");
171
+ const message = field(payload, "message");
172
+ const known = LOG_LEVELS.find((l) => l === level);
173
+ if (!known || typeof message !== "string") throw new BridgeError("BAD_REQUEST", "invalid log");
174
+ return { level: known, message: message.slice(0, LOG_MAX_LENGTH) };
175
+ }
176
+ function framesCopy(frames) {
177
+ if (!Array.isArray(frames) || frames.length > REPORT_MAX_FRAMES) return null;
178
+ const out = [];
179
+ for (let i = 0; i < frames.length; i += 1) {
180
+ if (!(i in frames)) return null;
181
+ const f = frames[i];
182
+ if (typeof f !== "string" || f.length > REPORT_FRAME_MAX_LENGTH) return null;
183
+ out.push(f);
184
+ }
185
+ return out;
186
+ }
187
+ function validateReport(payload) {
188
+ const kind = TEMPLATE_REPORT_KINDS.find((k) => k === field(payload, "kind"));
189
+ const message = field(payload, "message");
190
+ const frames = framesCopy(field(payload, "frames"));
191
+ const count = field(payload, "count");
192
+ if (!kind || typeof message !== "string" || message.length > REPORT_MESSAGE_MAX_LENGTH || frames === null || typeof count !== "number" || !Number.isInteger(count) || count < 1 || count > REPORT_COUNT_MAX) {
193
+ throw new BridgeError("BAD_REQUEST", "invalid report");
194
+ }
195
+ return Object.freeze({
196
+ kind,
197
+ message,
198
+ frames: Object.freeze(frames),
199
+ count
200
+ });
201
+ }
202
+
203
+ // src/host/accountSession.ts
204
+ var SESSION_PER_MINUTE = 5;
205
+ var SESSION_PER_FRAME = 20;
206
+ var OTP_SEND_PER_MINUTE = 3;
207
+ var OTP_VERIFY_PER_MINUTE = 10;
208
+ var LOGIN_BINDING_MS = 6e4;
209
+ var MAX_STRING = 2048;
210
+ var MAX_AGREEMENTS = 50;
211
+ var MAX_STATUS = 64;
212
+ var MAX_MESSAGE = 500;
213
+ var MARKETING_TARGETS = ["push", "email", "sms"];
214
+ var SIGNUP_COMMON = {
215
+ agreements: "agreements",
216
+ nickname: "string",
217
+ avatarImgPath: "string",
218
+ birthYear: "string",
219
+ birthMonth: "string",
220
+ birthDay: "string",
221
+ marketingNotificationTargets: "marketing",
222
+ phone: "string",
223
+ countryCallingCode: "string",
224
+ name: "string",
225
+ gender: "string",
226
+ phoneVerificationToken: "string"
227
+ };
228
+ var SESSION_SPECS = {
229
+ signup: {
230
+ fields: { email: "string", password: "string", ...SIGNUP_COMMON },
231
+ required: ["email", "password"]
232
+ },
233
+ signupSocial: { fields: { socialType: "string", ...SIGNUP_COMMON }, required: ["socialType"] },
234
+ loginAfterSignup: {
235
+ fields: { email: "string", password: "string", turnstileToken: "string" },
236
+ required: ["email", "password"]
237
+ },
238
+ phoneReverify: {
239
+ fields: { countryCallingCode: "string", phone: "string", phoneVerificationToken: "string" },
240
+ required: ["countryCallingCode", "phone", "phoneVerificationToken"]
241
+ }
242
+ };
243
+ var OTP_SPECS = {
244
+ sendSignup: {
245
+ endpoint: "send",
246
+ purpose: "SIGNUP",
247
+ spec: { fields: { phone: "string", locale: "string" }, required: ["phone"] }
248
+ },
249
+ sendPhoneChange: {
250
+ endpoint: "send",
251
+ purpose: "PHONE_CHANGE",
252
+ spec: { fields: { phone: "string", locale: "string" }, required: ["phone"] }
253
+ },
254
+ verifySignup: {
255
+ endpoint: "verify",
256
+ purpose: "SIGNUP",
257
+ spec: {
258
+ fields: { phone: "string", code: "string", requestId: "string" },
259
+ required: ["phone", "code"]
260
+ }
261
+ },
262
+ verifyPhoneChange: {
263
+ endpoint: "verify",
264
+ purpose: "PHONE_CHANGE",
265
+ spec: {
266
+ fields: { phone: "string", code: "string", requestId: "string" },
267
+ required: ["phone", "code"]
268
+ }
269
+ }
270
+ };
271
+ var OTP_DATA_FIELDS = {
272
+ send: ["requestId", "expiresInSeconds", "resendAvailableInSeconds", "maskedPhone"],
273
+ verify: ["verificationToken", "expiresAtSeconds", "phone"]
274
+ };
275
+ function bad() {
276
+ throw new BridgeError("BAD_REQUEST", "invalid account request");
277
+ }
278
+ function notAllowed() {
279
+ throw new BridgeError("NOT_ALLOWED", "not allowed for this placement");
280
+ }
66
281
  function obj(value) {
282
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
283
+ }
284
+ function str(value, max = MAX_STRING) {
285
+ return typeof value === "string" && value.length <= max ? value : void 0;
286
+ }
287
+ function cleanAgreements(value) {
288
+ if (!Array.isArray(value) || value.length > MAX_AGREEMENTS) bad();
289
+ return value.map((item) => {
290
+ const o = obj(item);
291
+ const termsId = str(o?.termsId);
292
+ if (!o || termsId === void 0) bad();
293
+ const termsVersion = o.termsVersion === void 0 ? void 0 : str(o.termsVersion);
294
+ const termsType = o.termsType === void 0 ? void 0 : str(o.termsType);
295
+ if (o.termsVersion !== void 0 && termsVersion === void 0) bad();
296
+ if (o.termsType !== void 0 && termsType === void 0) bad();
297
+ return {
298
+ termsId,
299
+ ...termsVersion !== void 0 ? { termsVersion } : {},
300
+ ...termsType !== void 0 ? { termsType } : {}
301
+ };
302
+ });
303
+ }
304
+ function cleanMarketing(value) {
305
+ if (!Array.isArray(value) || value.some((v) => !MARKETING_TARGETS.includes(v))) bad();
306
+ return [...value];
307
+ }
308
+ function cleanBody(raw, spec) {
309
+ const body = obj(raw);
310
+ if (!body) bad();
311
+ const out = {};
312
+ for (const [key, kind] of Object.entries(spec.fields)) {
313
+ if (!Object.prototype.hasOwnProperty.call(body, key) || body[key] === void 0) continue;
314
+ const value = body[key];
315
+ if (kind === "string") {
316
+ const s = str(value);
317
+ if (s === void 0) bad();
318
+ out[key] = s;
319
+ } else if (kind === "agreements") out[key] = cleanAgreements(value);
320
+ else out[key] = cleanMarketing(value);
321
+ }
322
+ for (const key of spec.required) {
323
+ if (typeof out[key] !== "string" || out[key].length === 0) bad();
324
+ }
325
+ return out;
326
+ }
327
+ function stripTokenKeys(value, depth = 0) {
328
+ if (depth > 8) return void 0;
329
+ if (Array.isArray(value)) return value.map((v) => stripTokenKeys(v, depth + 1));
330
+ const o = obj(value);
331
+ if (!o) return value;
332
+ return Object.fromEntries(
333
+ Object.entries(o).filter(([k]) => !/token/i.test(k)).map(([k, v]) => [k, stripTokenKeys(v, depth + 1)])
334
+ );
335
+ }
336
+ function cleanSessionResult(op, raw, hostOrigin) {
337
+ const r = obj(stripTokenKeys(raw)) ?? {};
338
+ const status = str(r.status, MAX_STATUS);
339
+ const message = typeof r.message === "string" ? r.message.slice(0, MAX_MESSAGE) : void 0;
340
+ const createdAt = op === "signup" || op === "signupSocial" ? str(r.createdAt, MAX_STATUS) : void 0;
341
+ let next;
342
+ const rawNext = obj(r.next);
343
+ if (r.ok === true && rawNext) {
344
+ try {
345
+ next = { path: validatePath({ path: rawNext.path }, hostOrigin), reload: true };
346
+ } catch {
347
+ next = void 0;
348
+ }
349
+ }
350
+ return {
351
+ ok: r.ok === true,
352
+ ...status !== void 0 ? { status } : {},
353
+ ...typeof r.code === "number" && Number.isFinite(r.code) ? { code: r.code } : {},
354
+ ...message !== void 0 ? { message } : {},
355
+ ...typeof r.httpStatus === "number" && Number.isInteger(r.httpStatus) ? { httpStatus: r.httpStatus } : {},
356
+ ...createdAt !== void 0 ? { createdAt } : {},
357
+ ...next ? { next } : {}
358
+ };
359
+ }
360
+ function cleanOtpResult(endpoint, raw) {
361
+ const r = obj(raw) ?? {};
362
+ const status = typeof r.status === "number" && Number.isInteger(r.status) ? r.status : 0;
363
+ const rawData = obj(r.data);
364
+ let data;
365
+ if (rawData) {
366
+ data = {};
367
+ for (const key of OTP_DATA_FIELDS[endpoint]) {
368
+ const v = rawData[key];
369
+ if (typeof v === "string" && v.length <= MAX_STRING) data[key] = v;
370
+ else if (typeof v === "number" && Number.isFinite(v)) data[key] = v;
371
+ }
372
+ }
373
+ const rawError = obj(r.error);
374
+ let error;
375
+ if (rawError) {
376
+ const code = str(rawError.code, MAX_STATUS);
377
+ const m = obj(rawError.message);
378
+ const en = m ? str(m.en, MAX_MESSAGE) : void 0;
379
+ const vi = m ? str(m.vi, MAX_MESSAGE) : void 0;
380
+ const retry = rawError.retryAfterSeconds;
381
+ error = {
382
+ ...code !== void 0 ? { code } : {},
383
+ ...en !== void 0 || vi !== void 0 ? { message: { ...en !== void 0 ? { en } : {}, ...vi !== void 0 ? { vi } : {} } } : {},
384
+ ...typeof retry === "number" && Number.isFinite(retry) ? { retryAfterSeconds: retry } : {}
385
+ };
386
+ }
387
+ return { ok: r.ok === true, status, ...data ? { data } : {}, ...error ? { error } : {} };
388
+ }
389
+ function hasAccountCapability(init) {
390
+ return init.surface === "page" && Array.isArray(init.capabilities) && init.capabilities.includes(ACCOUNT_SESSION_CAPABILITY);
391
+ }
392
+ var STATE_KEY = "__bstage_account_limits__";
393
+ var RELOAD_GRANT_MS = 6e4;
394
+ var WINDOW_MS = 6e4;
395
+ function defaultAccountStateStore(scope = "") {
396
+ const key = scope ? `${STATE_KEY}:${scope}` : STATE_KEY;
397
+ let memory = null;
398
+ const storage = () => {
399
+ try {
400
+ const s = globalThis.sessionStorage;
401
+ return s && typeof s.getItem === "function" ? s : void 0;
402
+ } catch {
403
+ return void 0;
404
+ }
405
+ };
406
+ return {
407
+ get() {
408
+ try {
409
+ return storage()?.getItem(key) ?? memory;
410
+ } catch {
411
+ return memory;
412
+ }
413
+ },
414
+ set(value) {
415
+ memory = value;
416
+ try {
417
+ storage()?.setItem(key, value);
418
+ } catch {
419
+ }
420
+ }
421
+ };
422
+ }
423
+ var EMPTY_STATE = { session: [], send: [], verify: [] };
424
+ function stamps(value) {
425
+ return Array.isArray(value) ? value.filter((t) => typeof t === "number" && Number.isFinite(t)) : [];
426
+ }
427
+ function readState(store) {
428
+ try {
429
+ const raw = store.get();
430
+ if (!raw) return EMPTY_STATE;
431
+ const v = JSON.parse(raw);
432
+ if (typeof v !== "object" || v === null) return EMPTY_STATE;
433
+ return { session: stamps(v.session), send: stamps(v.send), verify: stamps(v.verify) };
434
+ } catch {
435
+ return EMPTY_STATE;
436
+ }
437
+ }
438
+ function createAccountSessionHandler(ctx) {
439
+ const store = ctx.stateStore ?? defaultAccountStateStore(ctx.scope);
440
+ function take(kind, max) {
441
+ const now = Date.now();
442
+ const state = readState(store);
443
+ const recent = state[kind].filter((t) => now - t < WINDOW_MS);
444
+ if (recent.length >= max) return false;
445
+ const next = { ...state, [kind]: [...recent, now] };
446
+ store.set(JSON.stringify(next));
447
+ return true;
448
+ }
449
+ let sessionCount = 0;
450
+ let reloadGrantUntil;
451
+ let loginBinding;
452
+ function gate(impl) {
453
+ if (!ctx.enabled) notAllowed();
454
+ if (!impl) throw new BridgeError("UNSUPPORTED", "not supported by host");
455
+ return impl;
456
+ }
457
+ return {
458
+ async session(payload) {
459
+ const impl = gate(ctx.sessionImpl);
460
+ const p = obj(payload) ?? {};
461
+ const op = p.op;
462
+ if (!SESSION_OPS.includes(op)) bad();
463
+ const body = cleanBody(p.body, SESSION_SPECS[op]);
464
+ if (op === "loginAfterSignup") {
465
+ const binding = loginBinding;
466
+ if (!binding || Date.now() > binding.until || binding.email !== body.email) notAllowed();
467
+ }
468
+ if (sessionCount >= SESSION_PER_FRAME || !take("session", SESSION_PER_MINUTE)) {
469
+ throw new BridgeError("RATE_LIMITED", "too many session requests");
470
+ }
471
+ if (op === "loginAfterSignup") loginBinding = void 0;
472
+ sessionCount += 1;
473
+ let raw;
474
+ try {
475
+ raw = await impl(op, body);
476
+ } catch {
477
+ throw new BridgeError("BAD_REQUEST", "request failed");
478
+ }
479
+ const result = cleanSessionResult(op, raw, ctx.hostOrigin);
480
+ if (result.ok && result.status === "SUCCESS") reloadGrantUntil = Date.now() + RELOAD_GRANT_MS;
481
+ if (op === "signup" && result.ok && result.status === "LOGIN_REQUIRED") {
482
+ loginBinding = { email: body.email, until: Date.now() + LOGIN_BINDING_MS };
483
+ }
484
+ return result;
485
+ },
486
+ takeReload() {
487
+ const until = reloadGrantUntil;
488
+ reloadGrantUntil = void 0;
489
+ return until !== void 0 && Date.now() <= until;
490
+ },
491
+ async otp(payload) {
492
+ const impl = gate(ctx.otpImpl);
493
+ const p = obj(payload) ?? {};
494
+ const op = p.op;
495
+ if (!OTP_OPS.includes(op)) bad();
496
+ const { endpoint, purpose, spec } = OTP_SPECS[op];
497
+ const body = cleanBody(p.body, spec);
498
+ const allowed = endpoint === "send" ? take("send", OTP_SEND_PER_MINUTE) : take("verify", OTP_VERIFY_PER_MINUTE);
499
+ if (!allowed) throw new BridgeError("RATE_LIMITED", "too many otp requests");
500
+ let raw;
501
+ try {
502
+ raw = await impl({ op, endpoint, purpose, body });
503
+ } catch {
504
+ throw new BridgeError("NETWORK_ERROR", "network error");
505
+ }
506
+ return cleanOtpResult(endpoint, raw);
507
+ }
508
+ };
509
+ }
510
+ function buildAccountInit(init) {
511
+ const capabilities = Array.isArray(init.capabilities) ? init.capabilities.filter((c) => KNOWN_CAPABILITIES.includes(c)) : [];
512
+ if (!hasAccountCapability(init)) {
513
+ return capabilities.length > 0 ? { capabilities: Object.freeze(capabilities) } : {};
514
+ }
515
+ const q = obj(init.query);
516
+ const socialType = q ? str(q.socialType, MAX_STATUS) : void 0;
517
+ const country = typeof init.country === "string" && /^[A-Za-z]{2,3}$/.test(init.country) ? init.country : void 0;
518
+ const s = obj(init.space);
519
+ const title = s ? str(s.title, 200) : void 0;
520
+ const corp = s ? obj(s.corporation) : void 0;
521
+ const corpName = corp ? str(corp.name, 200) : void 0;
522
+ const corpCountry = corp ? str(corp.country, 8) : void 0;
523
+ const r = obj(init.reverification);
524
+ const expiresAt = r ? str(r.expiresAt, MAX_STATUS) : void 0;
525
+ return {
526
+ capabilities: Object.freeze(capabilities),
527
+ query: socialType !== void 0 ? { socialType } : {},
528
+ ...country !== void 0 ? { country } : {},
529
+ ...s ? {
530
+ space: {
531
+ ...title !== void 0 ? { title } : {},
532
+ ...corp ? {
533
+ corporation: {
534
+ ...corpName !== void 0 ? { name: corpName } : {},
535
+ ...corpCountry !== void 0 ? { country: corpCountry } : {}
536
+ }
537
+ } : {}
538
+ }
539
+ } : {},
540
+ ...r ? {
541
+ reverification: {
542
+ available: r.available === true,
543
+ ...expiresAt !== void 0 ? { expiresAt } : {}
544
+ }
545
+ } : {}
546
+ };
547
+ }
548
+
549
+ // src/host/events.ts
550
+ function obj2(value) {
67
551
  return typeof value === "object" && value !== null ? value : {};
68
552
  }
69
553
  function sanitizeTheme(value) {
70
- return { dark: obj(value).dark === true };
554
+ return { dark: obj2(value).dark === true };
71
555
  }
72
556
  function sanitizeMember(value) {
73
- const m = obj(value);
557
+ const m = obj2(value);
74
558
  return {
75
559
  signedIn: m.signedIn === true,
76
560
  ...typeof m.nickname === "string" ? { nickname: m.nickname } : {}
77
561
  };
78
562
  }
79
563
  function sanitizeSlot(value) {
80
- const s = obj(value);
564
+ const s = obj2(value);
81
565
  return typeof s.id === "string" ? { id: s.id, context: s.context } : void 0;
82
566
  }
83
567
  function sanitizeTranslations(value) {
@@ -91,7 +575,7 @@ function sanitizeTranslations(value) {
91
575
  );
92
576
  }
93
577
  function sanitizeEvent(type, payload) {
94
- const p = obj(payload);
578
+ const p = obj2(payload);
95
579
  switch (type) {
96
580
  case "theme":
97
581
  return sanitizeTheme(p);
@@ -135,7 +619,8 @@ function buildInit(init, hostOrigin, partnerOrigins, policy) {
135
619
  maxRequestsPerMinute: policy.maxRequestsPerMinute
136
620
  },
137
621
  partnerOrigins,
138
- ...translations ? { translations } : {}
622
+ ...translations ? { translations } : {},
623
+ ...buildAccountInit(init)
139
624
  });
140
625
  }
141
626
  function applyEvent(init, type, payload) {
@@ -193,128 +678,6 @@ function handleStorage(scope, req) {
193
678
  throw new BridgeError("BAD_REQUEST", "invalid storage op");
194
679
  }
195
680
 
196
- // src/host/validators.ts
197
- var MAX_PATH_LENGTH = 2048;
198
- var TOAST_MAX_LENGTH = 500;
199
- var TRACK_NAME_MAX_LENGTH = 100;
200
- var TRACK_PARAMS_MAX_BYTES = 4096;
201
- var RESIZE_MAX_HEIGHT = 2e5;
202
- var LOG_MAX_LENGTH = 2e3;
203
- var UNSAFE_KEYS = ["__proto__", "constructor", "prototype"];
204
- var TOAST_KINDS = ["info", "success", "warning", "error"];
205
- var LOG_LEVELS = ["debug", "info", "warn", "error"];
206
- function field(payload, key) {
207
- return typeof payload === "object" && payload !== null ? payload[key] : void 0;
208
- }
209
- function validatePath(payload, hostOrigin) {
210
- const path = field(payload, "path");
211
- if (typeof path !== "string" || path.length === 0 || path.length > MAX_PATH_LENGTH || !path.startsWith("/") || path.startsWith("//") || // eslint-disable-next-line no-control-regex -- 제어문자를 거르는 것이 목적이다
212
- /[\s\\\u0000-\u001f\u007f]/.test(path)) {
213
- throw new BridgeError("BAD_REQUEST", "invalid path");
214
- }
215
- let resolved;
216
- try {
217
- resolved = new URL(path, hostOrigin);
218
- } catch {
219
- throw new BridgeError("BAD_REQUEST", "invalid path");
220
- }
221
- if (resolved.origin !== new URL(hostOrigin).origin || resolved.pathname.startsWith("//")) {
222
- throw new BridgeError("BAD_REQUEST", "invalid path");
223
- }
224
- if (!checkPath(resolved.pathname, { forbidDoubleSlash: true }).ok) {
225
- throw new BridgeError("BAD_REQUEST", "invalid path");
226
- }
227
- return resolved.pathname + resolved.search + resolved.hash;
228
- }
229
- function validateExternalUrl(payload) {
230
- const raw = field(payload, "url");
231
- if (typeof raw !== "string") throw new BridgeError("BAD_REQUEST", "invalid url");
232
- let url;
233
- try {
234
- url = new URL(raw);
235
- } catch {
236
- throw new BridgeError("BAD_REQUEST", "invalid url");
237
- }
238
- if (url.protocol !== "https:" || url.username !== "" || url.password !== "") {
239
- throw new BridgeError("FORBIDDEN_DESTINATION", "only https urls can be opened");
240
- }
241
- return url.href;
242
- }
243
- function validateToast(payload) {
244
- const message = field(payload, "message");
245
- if (typeof message !== "string") throw new BridgeError("BAD_REQUEST", "invalid toast");
246
- const kind = field(payload, "kind");
247
- const known = TOAST_KINDS.find((k) => k === kind);
248
- return { message: message.slice(0, TOAST_MAX_LENGTH), ...known ? { kind: known } : {} };
249
- }
250
- function validateHeight(payload) {
251
- const height = field(payload, "height");
252
- if (typeof height !== "number" || !Number.isFinite(height)) {
253
- throw new BridgeError("BAD_REQUEST", "invalid height");
254
- }
255
- return Math.min(RESIZE_MAX_HEIGHT, Math.max(0, Math.round(height)));
256
- }
257
- function validateTrack(payload) {
258
- const name = field(payload, "name");
259
- const params = field(payload, "params");
260
- if (typeof name !== "string" || name.length === 0 || name.length > TRACK_NAME_MAX_LENGTH) {
261
- throw new BridgeError("BAD_REQUEST", "invalid track name");
262
- }
263
- if (params === void 0) return { name };
264
- if (typeof params !== "object" || params === null || Array.isArray(params)) {
265
- throw new BridgeError("BAD_REQUEST", "invalid track params");
266
- }
267
- let serialized;
268
- try {
269
- serialized = JSON.stringify(params);
270
- } catch {
271
- throw new BridgeError("BAD_REQUEST", "invalid track params");
272
- }
273
- if (new TextEncoder().encode(serialized).length > TRACK_PARAMS_MAX_BYTES) {
274
- throw new BridgeError("BAD_REQUEST", "track params too large");
275
- }
276
- return {
277
- name,
278
- params: JSON.parse(
279
- serialized,
280
- (key, value) => UNSAFE_KEYS.includes(key) ? void 0 : value
281
- )
282
- };
283
- }
284
- function validateLog(payload) {
285
- const level = field(payload, "level");
286
- const message = field(payload, "message");
287
- const known = LOG_LEVELS.find((l) => l === level);
288
- if (!known || typeof message !== "string") throw new BridgeError("BAD_REQUEST", "invalid log");
289
- return { level: known, message: message.slice(0, LOG_MAX_LENGTH) };
290
- }
291
- function framesCopy(frames) {
292
- if (!Array.isArray(frames) || frames.length > REPORT_MAX_FRAMES) return null;
293
- const out = [];
294
- for (let i = 0; i < frames.length; i += 1) {
295
- if (!(i in frames)) return null;
296
- const f = frames[i];
297
- if (typeof f !== "string" || f.length > REPORT_FRAME_MAX_LENGTH) return null;
298
- out.push(f);
299
- }
300
- return out;
301
- }
302
- function validateReport(payload) {
303
- const kind = TEMPLATE_REPORT_KINDS.find((k) => k === field(payload, "kind"));
304
- const message = field(payload, "message");
305
- const frames = framesCopy(field(payload, "frames"));
306
- const count = field(payload, "count");
307
- if (!kind || typeof message !== "string" || message.length > REPORT_MESSAGE_MAX_LENGTH || frames === null || typeof count !== "number" || !Number.isInteger(count) || count < 1 || count > REPORT_COUNT_MAX) {
308
- throw new BridgeError("BAD_REQUEST", "invalid report");
309
- }
310
- return Object.freeze({
311
- kind,
312
- message,
313
- frames: Object.freeze(frames),
314
- count
315
- });
316
- }
317
-
318
681
  // src/host/createBridgeHost.ts
319
682
  var OPAQUE_ORIGIN = "null";
320
683
  var UNLIMITED_REQUESTS = ["resize"];
@@ -410,8 +773,13 @@ async function dispatch(ctx, type, payload) {
410
773
  return runFetch(ctx, payload);
411
774
  case "navigate": {
412
775
  const path = validatePath(payload, ctx.hostOrigin);
776
+ const navOptions = validateNavigateOptions(payload);
777
+ if (navOptions?.reload && !ctx.account.takeReload()) {
778
+ throw new BridgeError("NOT_ALLOWED", "reload not allowed");
779
+ }
413
780
  if (!h.navigate) unsupported();
414
- h.navigate(path);
781
+ if (navOptions) h.navigate(path, navOptions);
782
+ else h.navigate(path);
415
783
  return EMPTY;
416
784
  }
417
785
  case "back":
@@ -461,6 +829,10 @@ async function dispatch(ctx, type, payload) {
461
829
  }
462
830
  return EMPTY;
463
831
  }
832
+ case "session":
833
+ return ctx.account.session(payload);
834
+ case "otp":
835
+ return ctx.account.otp(payload);
464
836
  }
465
837
  }
466
838
  function failure(code, message) {
@@ -504,6 +876,12 @@ function assertOptions(options) {
504
876
  if (options.onDispose !== void 0 && typeof options.onDispose !== "function") {
505
877
  throw new TypeError("[bstage-bridge] onDispose\uB294 \uD568\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4");
506
878
  }
879
+ if (options.sessionImpl !== void 0 && typeof options.sessionImpl !== "function") {
880
+ throw new TypeError("[bstage-bridge] sessionImpl\uC740 \uD568\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4");
881
+ }
882
+ if (options.otpImpl !== void 0 && typeof options.otpImpl !== "function") {
883
+ throw new TypeError("[bstage-bridge] otpImpl\uC740 \uD568\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4");
884
+ }
507
885
  if (options.onTemplateReport !== void 0 && typeof options.onTemplateReport !== "function") {
508
886
  throw new TypeError("[bstage-bridge] onTemplateReport\uB294 \uD568\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4");
509
887
  }
@@ -563,7 +941,16 @@ function createBridgeHost(options) {
563
941
  if (reportsTaken >= REPORTS_PER_SESSION) return false;
564
942
  reportsTaken += 1;
565
943
  return true;
566
- }
944
+ },
945
+ // 권한은 생성 시점의 init으로 한 번 정한다 — 이후 send()로 바뀌지 않는다.
946
+ account: createAccountSessionHandler({
947
+ enabled: hasAccountCapability(options.init),
948
+ hostOrigin,
949
+ sessionImpl: options.sessionImpl,
950
+ otpImpl: options.otpImpl,
951
+ ...options.accountStateStore ? { stateStore: options.accountStateStore } : {},
952
+ scope: `${options.init.spaceId}\0${options.init.placementId}`
953
+ })
567
954
  };
568
955
  function post(target, envelope) {
569
956
  if (disposed) return;
@@ -661,6 +1048,7 @@ function createBridgeHost(options) {
661
1048
  };
662
1049
  }
663
1050
  export {
1051
+ ACCOUNT_SESSION_CAPABILITY,
664
1052
  ALLOWED_METHODS,
665
1053
  ALLOWED_REQUEST_HEADERS,
666
1054
  BRIDGE_SURFACES,
@@ -669,18 +1057,24 @@ export {
669
1057
  DEFAULT_POLICY,
670
1058
  HOST_ONLY_HEADERS,
671
1059
  IFRAME_ATTRIBUTES,
1060
+ LOGIN_BINDING_MS,
672
1061
  MAX_DECODE_PASSES,
673
1062
  MAX_PARTNER_ORIGINS,
674
1063
  MAX_PASS_THROUGH_HEADERS,
1064
+ OTP_SEND_PER_MINUTE,
1065
+ OTP_VERIFY_PER_MINUTE,
675
1066
  REPORTS_PER_SESSION,
676
1067
  ROUTING_HEADERS,
677
1068
  ROUTING_HEADER_PREFIXES,
1069
+ SESSION_PER_FRAME,
1070
+ SESSION_PER_MINUTE,
678
1071
  checkPath,
679
1072
  classifyDestination,
680
1073
  createBridgeHost,
681
1074
  createNonce,
682
1075
  createSession,
683
1076
  createSrcdoc,
1077
+ hasAccountCapability,
684
1078
  isAllowedGatewayPath,
685
1079
  isBridgeSurface,
686
1080
  isValidSession,
@@ -688,5 +1082,6 @@ export {
688
1082
  normalizePinnedHeaders,
689
1083
  prepareFetch,
690
1084
  resolveDestination,
691
- resolvePolicy
1085
+ resolvePolicy,
1086
+ stripTokenKeys
692
1087
  };