@bstage-sdk/bridge 0.14.1 → 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.cjs CHANGED
@@ -20,6 +20,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/host/index.ts
21
21
  var host_exports = {};
22
22
  __export(host_exports, {
23
+ ACCOUNT_SESSION_CAPABILITY: () => ACCOUNT_SESSION_CAPABILITY,
23
24
  ALLOWED_METHODS: () => ALLOWED_METHODS,
24
25
  ALLOWED_REQUEST_HEADERS: () => ALLOWED_REQUEST_HEADERS,
25
26
  BRIDGE_SURFACES: () => BRIDGE_SURFACES,
@@ -28,18 +29,24 @@ __export(host_exports, {
28
29
  DEFAULT_POLICY: () => DEFAULT_POLICY,
29
30
  HOST_ONLY_HEADERS: () => HOST_ONLY_HEADERS,
30
31
  IFRAME_ATTRIBUTES: () => IFRAME_ATTRIBUTES,
32
+ LOGIN_BINDING_MS: () => LOGIN_BINDING_MS,
31
33
  MAX_DECODE_PASSES: () => MAX_DECODE_PASSES,
32
34
  MAX_PARTNER_ORIGINS: () => MAX_PARTNER_ORIGINS,
33
35
  MAX_PASS_THROUGH_HEADERS: () => MAX_PASS_THROUGH_HEADERS,
36
+ OTP_SEND_PER_MINUTE: () => OTP_SEND_PER_MINUTE,
37
+ OTP_VERIFY_PER_MINUTE: () => OTP_VERIFY_PER_MINUTE,
34
38
  REPORTS_PER_SESSION: () => REPORTS_PER_SESSION,
35
39
  ROUTING_HEADERS: () => ROUTING_HEADERS,
36
40
  ROUTING_HEADER_PREFIXES: () => ROUTING_HEADER_PREFIXES,
41
+ SESSION_PER_FRAME: () => SESSION_PER_FRAME,
42
+ SESSION_PER_MINUTE: () => SESSION_PER_MINUTE,
37
43
  checkPath: () => checkPath,
38
44
  classifyDestination: () => classifyDestination,
39
45
  createBridgeHost: () => createBridgeHost,
40
46
  createNonce: () => createNonce,
41
47
  createSession: () => createSession,
42
48
  createSrcdoc: () => createSrcdoc,
49
+ hasAccountCapability: () => hasAccountCapability,
43
50
  isAllowedGatewayPath: () => isAllowedGatewayPath,
44
51
  isBridgeSurface: () => isBridgeSurface,
45
52
  isValidSession: () => isValidSession,
@@ -47,7 +54,8 @@ __export(host_exports, {
47
54
  normalizePinnedHeaders: () => normalizePinnedHeaders,
48
55
  prepareFetch: () => prepareFetch,
49
56
  resolveDestination: () => resolveDestination,
50
- resolvePolicy: () => resolvePolicy
57
+ resolvePolicy: () => resolvePolicy,
58
+ stripTokenKeys: () => stripTokenKeys
51
59
  });
52
60
  module.exports = __toCommonJS(host_exports);
53
61
 
@@ -81,7 +89,9 @@ var BRIDGE_ERROR_CODES = [
81
89
  "BAD_REQUEST",
82
90
  "TIMEOUT",
83
91
  "NETWORK_ERROR",
84
- "UNSUPPORTED"
92
+ "UNSUPPORTED",
93
+ // 권한(capability) 없는 배치의 계정 요청, 또는 결속 조건을 벗어난 세션 요청.
94
+ "NOT_ALLOWED"
85
95
  ];
86
96
  var BridgeError = class extends Error {
87
97
  constructor(code, message) {
@@ -108,7 +118,9 @@ var REQUEST_TYPES = [
108
118
  "track",
109
119
  "storage",
110
120
  "log",
111
- "report"
121
+ "report",
122
+ "session",
123
+ "otp"
112
124
  ];
113
125
  var HOST_EVENT_TYPES = ["slot.context", "locale", "member", "theme", "visibility"];
114
126
  var READY_EVENT = "ready";
@@ -118,6 +130,15 @@ var BRIDGE_SURFACES = ["page", "slot"];
118
130
  function isBridgeSurface(value) {
119
131
  return BRIDGE_SURFACES.includes(value);
120
132
  }
133
+ var ACCOUNT_SESSION_CAPABILITY = "account-session";
134
+ var KNOWN_CAPABILITIES = [ACCOUNT_SESSION_CAPABILITY];
135
+ var SESSION_OPS = ["signup", "signupSocial", "loginAfterSignup", "phoneReverify"];
136
+ var OTP_OPS = [
137
+ "sendSignup",
138
+ "sendPhoneChange",
139
+ "verifySignup",
140
+ "verifyPhoneChange"
141
+ ];
121
142
  var TEMPLATE_REPORT_KINDS = ["error", "rejection", "load"];
122
143
  var REPORT_MESSAGE_MAX_LENGTH = 300;
123
144
  var REPORT_MAX_FRAMES = 10;
@@ -185,10 +206,10 @@ function hasDotSegment(form) {
185
206
  function checkPath(pathname, options = {}) {
186
207
  const forms = decodeStages(pathname);
187
208
  if (!forms) return REJECT;
188
- const bad = forms.some(
209
+ const bad2 = forms.some(
189
210
  (form) => UNSAFE_CHARS_RE.test(form) || hasDotSegment(form) || options.forbidDoubleSlash === true && form.includes("//")
190
211
  );
191
- return bad ? REJECT : { ok: true, forms: Object.freeze(forms) };
212
+ return bad2 ? REJECT : { ok: true, forms: Object.freeze(forms) };
192
213
  }
193
214
 
194
215
  // src/host/policy.ts
@@ -498,36 +519,516 @@ function prepareFetch(payload, ctx) {
498
519
  // src/host/rateLimiter.ts
499
520
  var DEFAULT_WINDOW_MS = 6e4;
500
521
  function createRateLimiter(max, windowMs = DEFAULT_WINDOW_MS) {
501
- let stamps = [];
522
+ let stamps2 = [];
502
523
  return {
503
524
  take(now = Date.now()) {
504
- const recent = stamps.filter((t) => now - t < windowMs);
525
+ const recent = stamps2.filter((t) => now - t < windowMs);
505
526
  if (recent.length >= max) {
506
- stamps = recent;
527
+ stamps2 = recent;
507
528
  return false;
508
529
  }
509
- stamps = [...recent, now];
530
+ stamps2 = [...recent, now];
510
531
  return true;
511
532
  }
512
533
  };
513
534
  }
514
535
 
515
- // src/host/events.ts
536
+ // src/host/validators.ts
537
+ var MAX_PATH_LENGTH = 2048;
538
+ var TOAST_MAX_LENGTH = 500;
539
+ var TRACK_NAME_MAX_LENGTH = 100;
540
+ var TRACK_PARAMS_MAX_BYTES = 4096;
541
+ var RESIZE_MAX_HEIGHT = 2e5;
542
+ var LOG_MAX_LENGTH = 2e3;
543
+ var UNSAFE_KEYS = ["__proto__", "constructor", "prototype"];
544
+ var TOAST_KINDS = ["info", "success", "warning", "error"];
545
+ var LOG_LEVELS = ["debug", "info", "warn", "error"];
546
+ function field(payload, key) {
547
+ return typeof payload === "object" && payload !== null ? payload[key] : void 0;
548
+ }
549
+ function validatePath(payload, hostOrigin) {
550
+ const path = field(payload, "path");
551
+ if (typeof path !== "string" || path.length === 0 || path.length > MAX_PATH_LENGTH || !path.startsWith("/") || path.startsWith("//") || // eslint-disable-next-line no-control-regex -- 제어문자를 거르는 것이 목적이다
552
+ /[\s\\\u0000-\u001f\u007f]/.test(path)) {
553
+ throw new BridgeError("BAD_REQUEST", "invalid path");
554
+ }
555
+ let resolved;
556
+ try {
557
+ resolved = new URL(path, hostOrigin);
558
+ } catch {
559
+ throw new BridgeError("BAD_REQUEST", "invalid path");
560
+ }
561
+ if (resolved.origin !== new URL(hostOrigin).origin || resolved.pathname.startsWith("//")) {
562
+ throw new BridgeError("BAD_REQUEST", "invalid path");
563
+ }
564
+ if (!checkPath(resolved.pathname, { forbidDoubleSlash: true }).ok) {
565
+ throw new BridgeError("BAD_REQUEST", "invalid path");
566
+ }
567
+ return resolved.pathname + resolved.search + resolved.hash;
568
+ }
569
+ function validateNavigateOptions(payload) {
570
+ const replace = field(payload, "replace");
571
+ const reload = field(payload, "reload");
572
+ if (replace !== void 0 && typeof replace !== "boolean") {
573
+ throw new BridgeError("BAD_REQUEST", "invalid navigate options");
574
+ }
575
+ if (reload !== void 0 && typeof reload !== "boolean") {
576
+ throw new BridgeError("BAD_REQUEST", "invalid navigate options");
577
+ }
578
+ if (replace !== true && reload !== true) return void 0;
579
+ return { ...replace === true ? { replace } : {}, ...reload === true ? { reload } : {} };
580
+ }
581
+ function validateExternalUrl(payload) {
582
+ const raw = field(payload, "url");
583
+ if (typeof raw !== "string") throw new BridgeError("BAD_REQUEST", "invalid url");
584
+ let url;
585
+ try {
586
+ url = new URL(raw);
587
+ } catch {
588
+ throw new BridgeError("BAD_REQUEST", "invalid url");
589
+ }
590
+ if (url.protocol !== "https:" || url.username !== "" || url.password !== "") {
591
+ throw new BridgeError("FORBIDDEN_DESTINATION", "only https urls can be opened");
592
+ }
593
+ return url.href;
594
+ }
595
+ function validateToast(payload) {
596
+ const message = field(payload, "message");
597
+ if (typeof message !== "string") throw new BridgeError("BAD_REQUEST", "invalid toast");
598
+ const kind = field(payload, "kind");
599
+ const known = TOAST_KINDS.find((k) => k === kind);
600
+ return { message: message.slice(0, TOAST_MAX_LENGTH), ...known ? { kind: known } : {} };
601
+ }
602
+ function validateHeight(payload) {
603
+ const height = field(payload, "height");
604
+ if (typeof height !== "number" || !Number.isFinite(height)) {
605
+ throw new BridgeError("BAD_REQUEST", "invalid height");
606
+ }
607
+ return Math.min(RESIZE_MAX_HEIGHT, Math.max(0, Math.round(height)));
608
+ }
609
+ function validateTrack(payload) {
610
+ const name = field(payload, "name");
611
+ const params = field(payload, "params");
612
+ if (typeof name !== "string" || name.length === 0 || name.length > TRACK_NAME_MAX_LENGTH) {
613
+ throw new BridgeError("BAD_REQUEST", "invalid track name");
614
+ }
615
+ if (params === void 0) return { name };
616
+ if (typeof params !== "object" || params === null || Array.isArray(params)) {
617
+ throw new BridgeError("BAD_REQUEST", "invalid track params");
618
+ }
619
+ let serialized;
620
+ try {
621
+ serialized = JSON.stringify(params);
622
+ } catch {
623
+ throw new BridgeError("BAD_REQUEST", "invalid track params");
624
+ }
625
+ if (new TextEncoder().encode(serialized).length > TRACK_PARAMS_MAX_BYTES) {
626
+ throw new BridgeError("BAD_REQUEST", "track params too large");
627
+ }
628
+ return {
629
+ name,
630
+ params: JSON.parse(
631
+ serialized,
632
+ (key, value) => UNSAFE_KEYS.includes(key) ? void 0 : value
633
+ )
634
+ };
635
+ }
636
+ function validateLog(payload) {
637
+ const level = field(payload, "level");
638
+ const message = field(payload, "message");
639
+ const known = LOG_LEVELS.find((l) => l === level);
640
+ if (!known || typeof message !== "string") throw new BridgeError("BAD_REQUEST", "invalid log");
641
+ return { level: known, message: message.slice(0, LOG_MAX_LENGTH) };
642
+ }
643
+ function framesCopy(frames) {
644
+ if (!Array.isArray(frames) || frames.length > REPORT_MAX_FRAMES) return null;
645
+ const out = [];
646
+ for (let i = 0; i < frames.length; i += 1) {
647
+ if (!(i in frames)) return null;
648
+ const f = frames[i];
649
+ if (typeof f !== "string" || f.length > REPORT_FRAME_MAX_LENGTH) return null;
650
+ out.push(f);
651
+ }
652
+ return out;
653
+ }
654
+ function validateReport(payload) {
655
+ const kind = TEMPLATE_REPORT_KINDS.find((k) => k === field(payload, "kind"));
656
+ const message = field(payload, "message");
657
+ const frames = framesCopy(field(payload, "frames"));
658
+ const count = field(payload, "count");
659
+ 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) {
660
+ throw new BridgeError("BAD_REQUEST", "invalid report");
661
+ }
662
+ return Object.freeze({
663
+ kind,
664
+ message,
665
+ frames: Object.freeze(frames),
666
+ count
667
+ });
668
+ }
669
+
670
+ // src/host/accountSession.ts
671
+ var SESSION_PER_MINUTE = 5;
672
+ var SESSION_PER_FRAME = 20;
673
+ var OTP_SEND_PER_MINUTE = 3;
674
+ var OTP_VERIFY_PER_MINUTE = 10;
675
+ var LOGIN_BINDING_MS = 6e4;
676
+ var MAX_STRING = 2048;
677
+ var MAX_AGREEMENTS = 50;
678
+ var MAX_STATUS = 64;
679
+ var MAX_MESSAGE = 500;
680
+ var MARKETING_TARGETS = ["push", "email", "sms"];
681
+ var SIGNUP_COMMON = {
682
+ agreements: "agreements",
683
+ nickname: "string",
684
+ avatarImgPath: "string",
685
+ birthYear: "string",
686
+ birthMonth: "string",
687
+ birthDay: "string",
688
+ marketingNotificationTargets: "marketing",
689
+ phone: "string",
690
+ countryCallingCode: "string",
691
+ name: "string",
692
+ gender: "string",
693
+ phoneVerificationToken: "string"
694
+ };
695
+ var SESSION_SPECS = {
696
+ signup: {
697
+ fields: { email: "string", password: "string", ...SIGNUP_COMMON },
698
+ required: ["email", "password"]
699
+ },
700
+ signupSocial: { fields: { socialType: "string", ...SIGNUP_COMMON }, required: ["socialType"] },
701
+ loginAfterSignup: {
702
+ fields: { email: "string", password: "string", turnstileToken: "string" },
703
+ required: ["email", "password"]
704
+ },
705
+ phoneReverify: {
706
+ fields: { countryCallingCode: "string", phone: "string", phoneVerificationToken: "string" },
707
+ required: ["countryCallingCode", "phone", "phoneVerificationToken"]
708
+ }
709
+ };
710
+ var OTP_SPECS = {
711
+ sendSignup: {
712
+ endpoint: "send",
713
+ purpose: "SIGNUP",
714
+ spec: { fields: { phone: "string", locale: "string" }, required: ["phone"] }
715
+ },
716
+ sendPhoneChange: {
717
+ endpoint: "send",
718
+ purpose: "PHONE_CHANGE",
719
+ spec: { fields: { phone: "string", locale: "string" }, required: ["phone"] }
720
+ },
721
+ verifySignup: {
722
+ endpoint: "verify",
723
+ purpose: "SIGNUP",
724
+ spec: {
725
+ fields: { phone: "string", code: "string", requestId: "string" },
726
+ required: ["phone", "code"]
727
+ }
728
+ },
729
+ verifyPhoneChange: {
730
+ endpoint: "verify",
731
+ purpose: "PHONE_CHANGE",
732
+ spec: {
733
+ fields: { phone: "string", code: "string", requestId: "string" },
734
+ required: ["phone", "code"]
735
+ }
736
+ }
737
+ };
738
+ var OTP_DATA_FIELDS = {
739
+ send: ["requestId", "expiresInSeconds", "resendAvailableInSeconds", "maskedPhone"],
740
+ verify: ["verificationToken", "expiresAtSeconds", "phone"]
741
+ };
742
+ function bad() {
743
+ throw new BridgeError("BAD_REQUEST", "invalid account request");
744
+ }
745
+ function notAllowed() {
746
+ throw new BridgeError("NOT_ALLOWED", "not allowed for this placement");
747
+ }
516
748
  function obj(value) {
749
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
750
+ }
751
+ function str(value, max = MAX_STRING) {
752
+ return typeof value === "string" && value.length <= max ? value : void 0;
753
+ }
754
+ function cleanAgreements(value) {
755
+ if (!Array.isArray(value) || value.length > MAX_AGREEMENTS) bad();
756
+ return value.map((item) => {
757
+ const o = obj(item);
758
+ const termsId = str(o?.termsId);
759
+ if (!o || termsId === void 0) bad();
760
+ const termsVersion = o.termsVersion === void 0 ? void 0 : str(o.termsVersion);
761
+ const termsType = o.termsType === void 0 ? void 0 : str(o.termsType);
762
+ if (o.termsVersion !== void 0 && termsVersion === void 0) bad();
763
+ if (o.termsType !== void 0 && termsType === void 0) bad();
764
+ return {
765
+ termsId,
766
+ ...termsVersion !== void 0 ? { termsVersion } : {},
767
+ ...termsType !== void 0 ? { termsType } : {}
768
+ };
769
+ });
770
+ }
771
+ function cleanMarketing(value) {
772
+ if (!Array.isArray(value) || value.some((v) => !MARKETING_TARGETS.includes(v))) bad();
773
+ return [...value];
774
+ }
775
+ function cleanBody(raw, spec) {
776
+ const body = obj(raw);
777
+ if (!body) bad();
778
+ const out = {};
779
+ for (const [key, kind] of Object.entries(spec.fields)) {
780
+ if (!Object.prototype.hasOwnProperty.call(body, key) || body[key] === void 0) continue;
781
+ const value = body[key];
782
+ if (kind === "string") {
783
+ const s = str(value);
784
+ if (s === void 0) bad();
785
+ out[key] = s;
786
+ } else if (kind === "agreements") out[key] = cleanAgreements(value);
787
+ else out[key] = cleanMarketing(value);
788
+ }
789
+ for (const key of spec.required) {
790
+ if (typeof out[key] !== "string" || out[key].length === 0) bad();
791
+ }
792
+ return out;
793
+ }
794
+ function stripTokenKeys(value, depth = 0) {
795
+ if (depth > 8) return void 0;
796
+ if (Array.isArray(value)) return value.map((v) => stripTokenKeys(v, depth + 1));
797
+ const o = obj(value);
798
+ if (!o) return value;
799
+ return Object.fromEntries(
800
+ Object.entries(o).filter(([k]) => !/token/i.test(k)).map(([k, v]) => [k, stripTokenKeys(v, depth + 1)])
801
+ );
802
+ }
803
+ function cleanSessionResult(op, raw, hostOrigin) {
804
+ const r = obj(stripTokenKeys(raw)) ?? {};
805
+ const status = str(r.status, MAX_STATUS);
806
+ const message = typeof r.message === "string" ? r.message.slice(0, MAX_MESSAGE) : void 0;
807
+ const createdAt = op === "signup" || op === "signupSocial" ? str(r.createdAt, MAX_STATUS) : void 0;
808
+ let next;
809
+ const rawNext = obj(r.next);
810
+ if (r.ok === true && rawNext) {
811
+ try {
812
+ next = { path: validatePath({ path: rawNext.path }, hostOrigin), reload: true };
813
+ } catch {
814
+ next = void 0;
815
+ }
816
+ }
817
+ return {
818
+ ok: r.ok === true,
819
+ ...status !== void 0 ? { status } : {},
820
+ ...typeof r.code === "number" && Number.isFinite(r.code) ? { code: r.code } : {},
821
+ ...message !== void 0 ? { message } : {},
822
+ ...typeof r.httpStatus === "number" && Number.isInteger(r.httpStatus) ? { httpStatus: r.httpStatus } : {},
823
+ ...createdAt !== void 0 ? { createdAt } : {},
824
+ ...next ? { next } : {}
825
+ };
826
+ }
827
+ function cleanOtpResult(endpoint, raw) {
828
+ const r = obj(raw) ?? {};
829
+ const status = typeof r.status === "number" && Number.isInteger(r.status) ? r.status : 0;
830
+ const rawData = obj(r.data);
831
+ let data;
832
+ if (rawData) {
833
+ data = {};
834
+ for (const key of OTP_DATA_FIELDS[endpoint]) {
835
+ const v = rawData[key];
836
+ if (typeof v === "string" && v.length <= MAX_STRING) data[key] = v;
837
+ else if (typeof v === "number" && Number.isFinite(v)) data[key] = v;
838
+ }
839
+ }
840
+ const rawError = obj(r.error);
841
+ let error;
842
+ if (rawError) {
843
+ const code = str(rawError.code, MAX_STATUS);
844
+ const m = obj(rawError.message);
845
+ const en = m ? str(m.en, MAX_MESSAGE) : void 0;
846
+ const vi = m ? str(m.vi, MAX_MESSAGE) : void 0;
847
+ const retry = rawError.retryAfterSeconds;
848
+ error = {
849
+ ...code !== void 0 ? { code } : {},
850
+ ...en !== void 0 || vi !== void 0 ? { message: { ...en !== void 0 ? { en } : {}, ...vi !== void 0 ? { vi } : {} } } : {},
851
+ ...typeof retry === "number" && Number.isFinite(retry) ? { retryAfterSeconds: retry } : {}
852
+ };
853
+ }
854
+ return { ok: r.ok === true, status, ...data ? { data } : {}, ...error ? { error } : {} };
855
+ }
856
+ function hasAccountCapability(init) {
857
+ return init.surface === "page" && Array.isArray(init.capabilities) && init.capabilities.includes(ACCOUNT_SESSION_CAPABILITY);
858
+ }
859
+ var STATE_KEY = "__bstage_account_limits__";
860
+ var RELOAD_GRANT_MS = 6e4;
861
+ var WINDOW_MS = 6e4;
862
+ function defaultAccountStateStore(scope = "") {
863
+ const key = scope ? `${STATE_KEY}:${scope}` : STATE_KEY;
864
+ let memory = null;
865
+ const storage = () => {
866
+ try {
867
+ const s = globalThis.sessionStorage;
868
+ return s && typeof s.getItem === "function" ? s : void 0;
869
+ } catch {
870
+ return void 0;
871
+ }
872
+ };
873
+ return {
874
+ get() {
875
+ try {
876
+ return storage()?.getItem(key) ?? memory;
877
+ } catch {
878
+ return memory;
879
+ }
880
+ },
881
+ set(value) {
882
+ memory = value;
883
+ try {
884
+ storage()?.setItem(key, value);
885
+ } catch {
886
+ }
887
+ }
888
+ };
889
+ }
890
+ var EMPTY_STATE = { session: [], send: [], verify: [] };
891
+ function stamps(value) {
892
+ return Array.isArray(value) ? value.filter((t) => typeof t === "number" && Number.isFinite(t)) : [];
893
+ }
894
+ function readState(store) {
895
+ try {
896
+ const raw = store.get();
897
+ if (!raw) return EMPTY_STATE;
898
+ const v = JSON.parse(raw);
899
+ if (typeof v !== "object" || v === null) return EMPTY_STATE;
900
+ return { session: stamps(v.session), send: stamps(v.send), verify: stamps(v.verify) };
901
+ } catch {
902
+ return EMPTY_STATE;
903
+ }
904
+ }
905
+ function createAccountSessionHandler(ctx) {
906
+ const store = ctx.stateStore ?? defaultAccountStateStore(ctx.scope);
907
+ function take(kind, max) {
908
+ const now = Date.now();
909
+ const state = readState(store);
910
+ const recent = state[kind].filter((t) => now - t < WINDOW_MS);
911
+ if (recent.length >= max) return false;
912
+ const next = { ...state, [kind]: [...recent, now] };
913
+ store.set(JSON.stringify(next));
914
+ return true;
915
+ }
916
+ let sessionCount = 0;
917
+ let reloadGrantUntil;
918
+ let loginBinding;
919
+ function gate(impl) {
920
+ if (!ctx.enabled) notAllowed();
921
+ if (!impl) throw new BridgeError("UNSUPPORTED", "not supported by host");
922
+ return impl;
923
+ }
924
+ return {
925
+ async session(payload) {
926
+ const impl = gate(ctx.sessionImpl);
927
+ const p = obj(payload) ?? {};
928
+ const op = p.op;
929
+ if (!SESSION_OPS.includes(op)) bad();
930
+ const body = cleanBody(p.body, SESSION_SPECS[op]);
931
+ if (op === "loginAfterSignup") {
932
+ const binding = loginBinding;
933
+ if (!binding || Date.now() > binding.until || binding.email !== body.email) notAllowed();
934
+ }
935
+ if (sessionCount >= SESSION_PER_FRAME || !take("session", SESSION_PER_MINUTE)) {
936
+ throw new BridgeError("RATE_LIMITED", "too many session requests");
937
+ }
938
+ if (op === "loginAfterSignup") loginBinding = void 0;
939
+ sessionCount += 1;
940
+ let raw;
941
+ try {
942
+ raw = await impl(op, body);
943
+ } catch {
944
+ throw new BridgeError("BAD_REQUEST", "request failed");
945
+ }
946
+ const result = cleanSessionResult(op, raw, ctx.hostOrigin);
947
+ if (result.ok && result.status === "SUCCESS") reloadGrantUntil = Date.now() + RELOAD_GRANT_MS;
948
+ if (op === "signup" && result.ok && result.status === "LOGIN_REQUIRED") {
949
+ loginBinding = { email: body.email, until: Date.now() + LOGIN_BINDING_MS };
950
+ }
951
+ return result;
952
+ },
953
+ takeReload() {
954
+ const until = reloadGrantUntil;
955
+ reloadGrantUntil = void 0;
956
+ return until !== void 0 && Date.now() <= until;
957
+ },
958
+ async otp(payload) {
959
+ const impl = gate(ctx.otpImpl);
960
+ const p = obj(payload) ?? {};
961
+ const op = p.op;
962
+ if (!OTP_OPS.includes(op)) bad();
963
+ const { endpoint, purpose, spec } = OTP_SPECS[op];
964
+ const body = cleanBody(p.body, spec);
965
+ const allowed = endpoint === "send" ? take("send", OTP_SEND_PER_MINUTE) : take("verify", OTP_VERIFY_PER_MINUTE);
966
+ if (!allowed) throw new BridgeError("RATE_LIMITED", "too many otp requests");
967
+ let raw;
968
+ try {
969
+ raw = await impl({ op, endpoint, purpose, body });
970
+ } catch {
971
+ throw new BridgeError("NETWORK_ERROR", "network error");
972
+ }
973
+ return cleanOtpResult(endpoint, raw);
974
+ }
975
+ };
976
+ }
977
+ function buildAccountInit(init) {
978
+ const capabilities = Array.isArray(init.capabilities) ? init.capabilities.filter((c) => KNOWN_CAPABILITIES.includes(c)) : [];
979
+ if (!hasAccountCapability(init)) {
980
+ return capabilities.length > 0 ? { capabilities: Object.freeze(capabilities) } : {};
981
+ }
982
+ const q = obj(init.query);
983
+ const socialType = q ? str(q.socialType, MAX_STATUS) : void 0;
984
+ const country = typeof init.country === "string" && /^[A-Za-z]{2,3}$/.test(init.country) ? init.country : void 0;
985
+ const s = obj(init.space);
986
+ const title = s ? str(s.title, 200) : void 0;
987
+ const corp = s ? obj(s.corporation) : void 0;
988
+ const corpName = corp ? str(corp.name, 200) : void 0;
989
+ const corpCountry = corp ? str(corp.country, 8) : void 0;
990
+ const r = obj(init.reverification);
991
+ const expiresAt = r ? str(r.expiresAt, MAX_STATUS) : void 0;
992
+ return {
993
+ capabilities: Object.freeze(capabilities),
994
+ query: socialType !== void 0 ? { socialType } : {},
995
+ ...country !== void 0 ? { country } : {},
996
+ ...s ? {
997
+ space: {
998
+ ...title !== void 0 ? { title } : {},
999
+ ...corp ? {
1000
+ corporation: {
1001
+ ...corpName !== void 0 ? { name: corpName } : {},
1002
+ ...corpCountry !== void 0 ? { country: corpCountry } : {}
1003
+ }
1004
+ } : {}
1005
+ }
1006
+ } : {},
1007
+ ...r ? {
1008
+ reverification: {
1009
+ available: r.available === true,
1010
+ ...expiresAt !== void 0 ? { expiresAt } : {}
1011
+ }
1012
+ } : {}
1013
+ };
1014
+ }
1015
+
1016
+ // src/host/events.ts
1017
+ function obj2(value) {
517
1018
  return typeof value === "object" && value !== null ? value : {};
518
1019
  }
519
1020
  function sanitizeTheme(value) {
520
- return { dark: obj(value).dark === true };
1021
+ return { dark: obj2(value).dark === true };
521
1022
  }
522
1023
  function sanitizeMember(value) {
523
- const m = obj(value);
1024
+ const m = obj2(value);
524
1025
  return {
525
1026
  signedIn: m.signedIn === true,
526
1027
  ...typeof m.nickname === "string" ? { nickname: m.nickname } : {}
527
1028
  };
528
1029
  }
529
1030
  function sanitizeSlot(value) {
530
- const s = obj(value);
1031
+ const s = obj2(value);
531
1032
  return typeof s.id === "string" ? { id: s.id, context: s.context } : void 0;
532
1033
  }
533
1034
  function sanitizeTranslations(value) {
@@ -541,7 +1042,7 @@ function sanitizeTranslations(value) {
541
1042
  );
542
1043
  }
543
1044
  function sanitizeEvent(type, payload) {
544
- const p = obj(payload);
1045
+ const p = obj2(payload);
545
1046
  switch (type) {
546
1047
  case "theme":
547
1048
  return sanitizeTheme(p);
@@ -585,7 +1086,8 @@ function buildInit(init, hostOrigin, partnerOrigins, policy) {
585
1086
  maxRequestsPerMinute: policy.maxRequestsPerMinute
586
1087
  },
587
1088
  partnerOrigins,
588
- ...translations ? { translations } : {}
1089
+ ...translations ? { translations } : {},
1090
+ ...buildAccountInit(init)
589
1091
  });
590
1092
  }
591
1093
  function applyEvent(init, type, payload) {
@@ -643,128 +1145,6 @@ function handleStorage(scope, req) {
643
1145
  throw new BridgeError("BAD_REQUEST", "invalid storage op");
644
1146
  }
645
1147
 
646
- // src/host/validators.ts
647
- var MAX_PATH_LENGTH = 2048;
648
- var TOAST_MAX_LENGTH = 500;
649
- var TRACK_NAME_MAX_LENGTH = 100;
650
- var TRACK_PARAMS_MAX_BYTES = 4096;
651
- var RESIZE_MAX_HEIGHT = 2e4;
652
- var LOG_MAX_LENGTH = 2e3;
653
- var UNSAFE_KEYS = ["__proto__", "constructor", "prototype"];
654
- var TOAST_KINDS = ["info", "success", "warning", "error"];
655
- var LOG_LEVELS = ["debug", "info", "warn", "error"];
656
- function field(payload, key) {
657
- return typeof payload === "object" && payload !== null ? payload[key] : void 0;
658
- }
659
- function validatePath(payload, hostOrigin) {
660
- const path = field(payload, "path");
661
- if (typeof path !== "string" || path.length === 0 || path.length > MAX_PATH_LENGTH || !path.startsWith("/") || path.startsWith("//") || // eslint-disable-next-line no-control-regex -- 제어문자를 거르는 것이 목적이다
662
- /[\s\\\u0000-\u001f\u007f]/.test(path)) {
663
- throw new BridgeError("BAD_REQUEST", "invalid path");
664
- }
665
- let resolved;
666
- try {
667
- resolved = new URL(path, hostOrigin);
668
- } catch {
669
- throw new BridgeError("BAD_REQUEST", "invalid path");
670
- }
671
- if (resolved.origin !== new URL(hostOrigin).origin || resolved.pathname.startsWith("//")) {
672
- throw new BridgeError("BAD_REQUEST", "invalid path");
673
- }
674
- if (!checkPath(resolved.pathname, { forbidDoubleSlash: true }).ok) {
675
- throw new BridgeError("BAD_REQUEST", "invalid path");
676
- }
677
- return resolved.pathname + resolved.search + resolved.hash;
678
- }
679
- function validateExternalUrl(payload) {
680
- const raw = field(payload, "url");
681
- if (typeof raw !== "string") throw new BridgeError("BAD_REQUEST", "invalid url");
682
- let url;
683
- try {
684
- url = new URL(raw);
685
- } catch {
686
- throw new BridgeError("BAD_REQUEST", "invalid url");
687
- }
688
- if (url.protocol !== "https:" || url.username !== "" || url.password !== "") {
689
- throw new BridgeError("FORBIDDEN_DESTINATION", "only https urls can be opened");
690
- }
691
- return url.href;
692
- }
693
- function validateToast(payload) {
694
- const message = field(payload, "message");
695
- if (typeof message !== "string") throw new BridgeError("BAD_REQUEST", "invalid toast");
696
- const kind = field(payload, "kind");
697
- const known = TOAST_KINDS.find((k) => k === kind);
698
- return { message: message.slice(0, TOAST_MAX_LENGTH), ...known ? { kind: known } : {} };
699
- }
700
- function validateHeight(payload) {
701
- const height = field(payload, "height");
702
- if (typeof height !== "number" || !Number.isFinite(height)) {
703
- throw new BridgeError("BAD_REQUEST", "invalid height");
704
- }
705
- return Math.min(RESIZE_MAX_HEIGHT, Math.max(0, Math.round(height)));
706
- }
707
- function validateTrack(payload) {
708
- const name = field(payload, "name");
709
- const params = field(payload, "params");
710
- if (typeof name !== "string" || name.length === 0 || name.length > TRACK_NAME_MAX_LENGTH) {
711
- throw new BridgeError("BAD_REQUEST", "invalid track name");
712
- }
713
- if (params === void 0) return { name };
714
- if (typeof params !== "object" || params === null || Array.isArray(params)) {
715
- throw new BridgeError("BAD_REQUEST", "invalid track params");
716
- }
717
- let serialized;
718
- try {
719
- serialized = JSON.stringify(params);
720
- } catch {
721
- throw new BridgeError("BAD_REQUEST", "invalid track params");
722
- }
723
- if (new TextEncoder().encode(serialized).length > TRACK_PARAMS_MAX_BYTES) {
724
- throw new BridgeError("BAD_REQUEST", "track params too large");
725
- }
726
- return {
727
- name,
728
- params: JSON.parse(
729
- serialized,
730
- (key, value) => UNSAFE_KEYS.includes(key) ? void 0 : value
731
- )
732
- };
733
- }
734
- function validateLog(payload) {
735
- const level = field(payload, "level");
736
- const message = field(payload, "message");
737
- const known = LOG_LEVELS.find((l) => l === level);
738
- if (!known || typeof message !== "string") throw new BridgeError("BAD_REQUEST", "invalid log");
739
- return { level: known, message: message.slice(0, LOG_MAX_LENGTH) };
740
- }
741
- function framesCopy(frames) {
742
- if (!Array.isArray(frames) || frames.length > REPORT_MAX_FRAMES) return null;
743
- const out = [];
744
- for (let i = 0; i < frames.length; i += 1) {
745
- if (!(i in frames)) return null;
746
- const f = frames[i];
747
- if (typeof f !== "string" || f.length > REPORT_FRAME_MAX_LENGTH) return null;
748
- out.push(f);
749
- }
750
- return out;
751
- }
752
- function validateReport(payload) {
753
- const kind = TEMPLATE_REPORT_KINDS.find((k) => k === field(payload, "kind"));
754
- const message = field(payload, "message");
755
- const frames = framesCopy(field(payload, "frames"));
756
- const count = field(payload, "count");
757
- 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) {
758
- throw new BridgeError("BAD_REQUEST", "invalid report");
759
- }
760
- return Object.freeze({
761
- kind,
762
- message,
763
- frames: Object.freeze(frames),
764
- count
765
- });
766
- }
767
-
768
1148
  // src/host/createBridgeHost.ts
769
1149
  var OPAQUE_ORIGIN = "null";
770
1150
  var UNLIMITED_REQUESTS = ["resize"];
@@ -860,8 +1240,13 @@ async function dispatch(ctx, type, payload) {
860
1240
  return runFetch(ctx, payload);
861
1241
  case "navigate": {
862
1242
  const path = validatePath(payload, ctx.hostOrigin);
1243
+ const navOptions = validateNavigateOptions(payload);
1244
+ if (navOptions?.reload && !ctx.account.takeReload()) {
1245
+ throw new BridgeError("NOT_ALLOWED", "reload not allowed");
1246
+ }
863
1247
  if (!h.navigate) unsupported();
864
- h.navigate(path);
1248
+ if (navOptions) h.navigate(path, navOptions);
1249
+ else h.navigate(path);
865
1250
  return EMPTY;
866
1251
  }
867
1252
  case "back":
@@ -911,6 +1296,10 @@ async function dispatch(ctx, type, payload) {
911
1296
  }
912
1297
  return EMPTY;
913
1298
  }
1299
+ case "session":
1300
+ return ctx.account.session(payload);
1301
+ case "otp":
1302
+ return ctx.account.otp(payload);
914
1303
  }
915
1304
  }
916
1305
  function failure(code, message) {
@@ -954,6 +1343,12 @@ function assertOptions(options) {
954
1343
  if (options.onDispose !== void 0 && typeof options.onDispose !== "function") {
955
1344
  throw new TypeError("[bstage-bridge] onDispose\uB294 \uD568\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4");
956
1345
  }
1346
+ if (options.sessionImpl !== void 0 && typeof options.sessionImpl !== "function") {
1347
+ throw new TypeError("[bstage-bridge] sessionImpl\uC740 \uD568\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4");
1348
+ }
1349
+ if (options.otpImpl !== void 0 && typeof options.otpImpl !== "function") {
1350
+ throw new TypeError("[bstage-bridge] otpImpl\uC740 \uD568\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4");
1351
+ }
957
1352
  if (options.onTemplateReport !== void 0 && typeof options.onTemplateReport !== "function") {
958
1353
  throw new TypeError("[bstage-bridge] onTemplateReport\uB294 \uD568\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4");
959
1354
  }
@@ -1013,7 +1408,16 @@ function createBridgeHost(options) {
1013
1408
  if (reportsTaken >= REPORTS_PER_SESSION) return false;
1014
1409
  reportsTaken += 1;
1015
1410
  return true;
1016
- }
1411
+ },
1412
+ // 권한은 생성 시점의 init으로 한 번 정한다 — 이후 send()로 바뀌지 않는다.
1413
+ account: createAccountSessionHandler({
1414
+ enabled: hasAccountCapability(options.init),
1415
+ hostOrigin,
1416
+ sessionImpl: options.sessionImpl,
1417
+ otpImpl: options.otpImpl,
1418
+ ...options.accountStateStore ? { stateStore: options.accountStateStore } : {},
1419
+ scope: `${options.init.spaceId}\0${options.init.placementId}`
1420
+ })
1017
1421
  };
1018
1422
  function post(target, envelope) {
1019
1423
  if (disposed) return;
@@ -1852,6 +2256,7 @@ ${script}
1852
2256
  }
1853
2257
  // Annotate the CommonJS export names for ESM import in node:
1854
2258
  0 && (module.exports = {
2259
+ ACCOUNT_SESSION_CAPABILITY,
1855
2260
  ALLOWED_METHODS,
1856
2261
  ALLOWED_REQUEST_HEADERS,
1857
2262
  BRIDGE_SURFACES,
@@ -1860,18 +2265,24 @@ ${script}
1860
2265
  DEFAULT_POLICY,
1861
2266
  HOST_ONLY_HEADERS,
1862
2267
  IFRAME_ATTRIBUTES,
2268
+ LOGIN_BINDING_MS,
1863
2269
  MAX_DECODE_PASSES,
1864
2270
  MAX_PARTNER_ORIGINS,
1865
2271
  MAX_PASS_THROUGH_HEADERS,
2272
+ OTP_SEND_PER_MINUTE,
2273
+ OTP_VERIFY_PER_MINUTE,
1866
2274
  REPORTS_PER_SESSION,
1867
2275
  ROUTING_HEADERS,
1868
2276
  ROUTING_HEADER_PREFIXES,
2277
+ SESSION_PER_FRAME,
2278
+ SESSION_PER_MINUTE,
1869
2279
  checkPath,
1870
2280
  classifyDestination,
1871
2281
  createBridgeHost,
1872
2282
  createNonce,
1873
2283
  createSession,
1874
2284
  createSrcdoc,
2285
+ hasAccountCapability,
1875
2286
  isAllowedGatewayPath,
1876
2287
  isBridgeSurface,
1877
2288
  isValidSession,
@@ -1879,5 +2290,6 @@ ${script}
1879
2290
  normalizePinnedHeaders,
1880
2291
  prepareFetch,
1881
2292
  resolveDestination,
1882
- resolvePolicy
2293
+ resolvePolicy,
2294
+ stripTokenKeys
1883
2295
  });