@wecode-team/cms-supabase-api 0.1.47 → 0.1.49

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/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var supabaseJs = require('@supabase/supabase-js');
4
+ var emailVerify = require('@wecode-team/email-verify');
4
5
  var jwt = require('jsonwebtoken');
5
6
  var bcrypt = require('bcryptjs');
6
7
 
@@ -695,6 +696,10 @@ function getSupabaseSetupSQL() {
695
696
  return "-- Supabase Setup SQL for we0-cms-supabase-hono-api\n-- \u8BF7\u5728 Supabase SQL \u7F16\u8F91\u5668\u4E2D\u6267\u884C\u4EE5\u4E0B\u5B8C\u6574\u811A\u672C\n\n-- Function to execute SQL queries\nCREATE OR REPLACE FUNCTION execute_sql(sql_query text)\nRETURNS json\nLANGUAGE plpgsql\nSECURITY DEFINER\nAS $$\nDECLARE\n result json;\n row_count integer;\nBEGIN\n EXECUTE sql_query;\n GET DIAGNOSTICS row_count = ROW_COUNT;\n RETURN json_build_object('success', true, 'rows_affected', row_count);\nEXCEPTION\n WHEN OTHERS THEN\n RETURN json_build_object('success', false, 'error', SQLERRM);\nEND;\n$$;\n\n-- Function to execute SQL with parameters (simplified version)\nCREATE OR REPLACE FUNCTION execute_sql_with_params(sql_query text, params json)\nRETURNS json\nLANGUAGE plpgsql\nSECURITY DEFINER\nAS $$\nDECLARE\n result json;\n row_count integer;\nBEGIN\n -- Note: This is a simplified version for basic use cases\n -- In production, you might want more sophisticated parameter binding\n EXECUTE sql_query;\n GET DIAGNOSTICS row_count = ROW_COUNT;\n RETURN json_build_object('success', true, 'rows_affected', row_count);\nEXCEPTION\n WHEN OTHERS THEN\n RETURN json_build_object('success', false, 'error', SQLERRM);\nEND;\n$$;\n\n-- Function to check if table exists\nCREATE OR REPLACE FUNCTION check_table_exists(input_table_name text)\nRETURNS boolean\nLANGUAGE plpgsql\nSECURITY DEFINER\nAS $$\nBEGIN\n RETURN EXISTS (\n SELECT 1 FROM information_schema.tables\n WHERE table_schema = 'public' \n AND table_name = input_table_name\n );\nEND;\n$$;\n\n-- Function to get table structure\nCREATE OR REPLACE FUNCTION get_table_structure(table_name text)\nRETURNS json\nLANGUAGE plpgsql\nSECURITY DEFINER\nAS $$\nDECLARE\n result json;\nBEGIN\n SELECT json_agg(\n json_build_object(\n 'column_name', column_name,\n 'data_type', data_type,\n 'is_nullable', is_nullable,\n 'column_default', column_default,\n 'character_maximum_length', character_maximum_length\n )\n ) INTO result\n FROM information_schema.columns\n WHERE table_schema = 'public' AND table_name = $1\n ORDER BY ordinal_position;\n \n RETURN COALESCE(result, '[]'::json);\nEND;\n$$;\n\n-- Function to create CMS models table if not exists\nCREATE OR REPLACE FUNCTION create_cms_models_table_if_not_exists()\nRETURNS json\nLANGUAGE plpgsql\nSECURITY DEFINER\nAS $$\nBEGIN\n -- Create the CMS models table\n CREATE TABLE IF NOT EXISTS \"_cms_models\" (\n id SERIAL PRIMARY KEY,\n name VARCHAR(100) NOT NULL,\n table_name VARCHAR(100) NOT NULL UNIQUE,\n json_schema JSONB NOT NULL,\n created_at TIMESTAMPTZ DEFAULT NOW(),\n updated_at TIMESTAMPTZ DEFAULT NOW()\n );\n \n -- Create or replace the trigger function for updating timestamps\n CREATE OR REPLACE FUNCTION update_updated_at_column()\n RETURNS TRIGGER AS $trigger$\n BEGIN\n NEW.updated_at = NOW();\n RETURN NEW;\n END;\n $trigger$ language 'plpgsql';\n \n -- Drop existing trigger if it exists and create new one\n DROP TRIGGER IF EXISTS update_cms_models_updated_at ON \"_cms_models\";\n CREATE TRIGGER update_cms_models_updated_at\n BEFORE UPDATE ON \"_cms_models\"\n FOR EACH ROW\n EXECUTE FUNCTION update_updated_at_column();\n \n RETURN json_build_object('success', true, 'message', 'CMS models table created successfully');\nEXCEPTION\n WHEN OTHERS THEN\n RETURN json_build_object('success', false, 'error', SQLERRM);\nEND;\n$$;\n\n-- Initialize the CMS models table\nSELECT create_cms_models_table_if_not_exists();\n\n-- Grant necessary permissions (adjust as needed for your security requirements)\n-- Note: Be careful with these permissions in production\nGRANT USAGE ON SCHEMA public TO anon, authenticated;\nGRANT ALL ON ALL TABLES IN SCHEMA public TO anon, authenticated;\nGRANT ALL ON ALL SEQUENCES IN SCHEMA public TO anon, authenticated;\nGRANT ALL ON ALL FUNCTIONS IN SCHEMA public TO anon, authenticated;\n\n-- Create RLS policies for the CMS models table (optional, adjust as needed)\nALTER TABLE \"_cms_models\" ENABLE ROW LEVEL SECURITY;\n\n-- Allow all operations for all users (development environment)\nCREATE POLICY \"Allow all operations\" ON \"_cms_models\"\n FOR ALL USING (true);\n\nCOMMENT ON TABLE \"_cms_models\" IS 'CMS models configuration table for we0-cms-supabase-hono-api';\nCOMMENT ON FUNCTION execute_sql(text) IS 'Execute SQL queries for dynamic table management';\nCOMMENT ON FUNCTION check_table_exists(text) IS 'Check if a table exists in the public schema';\nCOMMENT ON FUNCTION get_table_structure(text) IS 'Get the structure of a table';";
696
697
  }
697
698
 
699
+ var feishuAlertConfig = {
700
+ crudErrorWebhookUrls: ["https://open.feishu.cn/open-apis/bot/v2/hook/784e9470-c1fd-4e38-97a2-b9a1856c00b1"]
701
+ };
702
+
698
703
  function _classCallCheck(a, n) {
699
704
  if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
700
705
  }
@@ -1029,8 +1034,8 @@ function _defineProperty(e, r, t) {
1029
1034
  }) : e[r] = t, e;
1030
1035
  }
1031
1036
 
1032
- function ownKeys$5(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
1033
- function _objectSpread$5(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$5(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$5(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
1037
+ function ownKeys$3(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
1038
+ function _objectSpread$3(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$3(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$3(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
1034
1039
  function _createForOfIteratorHelper$2(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray$3(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
1035
1040
  function _unsupportedIterableToArray$3(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray$3(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray$3(r, a) : void 0; } }
1036
1041
  function _arrayLikeToArray$3(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
@@ -1038,6 +1043,7 @@ function _arrayLikeToArray$3(r, a) { (null == a || a > r.length) && (a = r.lengt
1038
1043
  var fieldTypeMapping = {
1039
1044
  string: "text",
1040
1045
  text: "text",
1046
+ richText: "text",
1041
1047
  integer: "int4",
1042
1048
  "float": "float8",
1043
1049
  "boolean": "bool",
@@ -2085,7 +2091,7 @@ var DynamicTableService = /*#__PURE__*/function () {
2085
2091
  throw error;
2086
2092
  case 2:
2087
2093
  return _context14.abrupt("return", (data || []).map(function (item) {
2088
- return _objectSpread$5({
2094
+ return _objectSpread$3({
2089
2095
  id: item.id,
2090
2096
  label: item[displayField] || "ID: ".concat(item.id)
2091
2097
  }, item);
@@ -2198,8 +2204,8 @@ function getDynamicTableService() {
2198
2204
  return defaultService$1;
2199
2205
  }
2200
2206
 
2201
- function ownKeys$4(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
2202
- function _objectSpread$4(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$4(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$4(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
2207
+ function ownKeys$2(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
2208
+ function _objectSpread$2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$2(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
2203
2209
  var AuthService = /*#__PURE__*/function () {
2204
2210
  function AuthService() {
2205
2211
  _classCallCheck(this, AuthService);
@@ -2376,7 +2382,7 @@ var AuthService = /*#__PURE__*/function () {
2376
2382
  return _regeneratorRuntime.wrap(function (_context4) {
2377
2383
  while (1) switch (_context4.prev = _context4.next) {
2378
2384
  case 0:
2379
- finalUserData = _objectSpread$4({
2385
+ finalUserData = _objectSpread$2({
2380
2386
  tableName: this.defaultTableName
2381
2387
  }, userData);
2382
2388
  _context4.prev = 1;
@@ -2434,7 +2440,7 @@ var AuthService = /*#__PURE__*/function () {
2434
2440
  case 0:
2435
2441
  updateData = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : {};
2436
2442
  // 设置默认值
2437
- finalUpdateData = _objectSpread$4({
2443
+ finalUpdateData = _objectSpread$2({
2438
2444
  tableName: this.defaultTableName
2439
2445
  }, updateData);
2440
2446
  _context5.prev = 1;
@@ -2842,8 +2848,8 @@ function _toConsumableArray(r) {
2842
2848
  return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray$2(r) || _nonIterableSpread();
2843
2849
  }
2844
2850
 
2845
- function ownKeys$3(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
2846
- function _objectSpread$3(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$3(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$3(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
2851
+ function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
2852
+ function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
2847
2853
  function _callSuper$1(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$1() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
2848
2854
  function _isNativeReflectConstruct$1() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$1 = function _isNativeReflectConstruct() { return !!t; })(); }
2849
2855
  // src/error.ts
@@ -3371,7 +3377,7 @@ var DEFAULT_LIMITS = {
3371
3377
  other: 10 * 1024 * 1024
3372
3378
  };
3373
3379
  function getSizeLimit(fileName, limits) {
3374
- var merged = _objectSpread$3(_objectSpread$3({}, DEFAULT_LIMITS), limits);
3380
+ var merged = _objectSpread$1(_objectSpread$1({}, DEFAULT_LIMITS), limits);
3375
3381
  if (isImage(fileName)) return merged.image;
3376
3382
  if (isVideo(fileName)) return merged.video;
3377
3383
  return merged.other;
@@ -3399,7 +3405,7 @@ function _compressImageBlob() {
3399
3405
  return _regeneratorRuntime.wrap(function (_context10) {
3400
3406
  while (1) switch (_context10.prev = _context10.next) {
3401
3407
  case 0:
3402
- opts = _objectSpread$3(_objectSpread$3({}, DEFAULT_COMPRESS), options);
3408
+ opts = _objectSpread$1(_objectSpread$1({}, DEFAULT_COMPRESS), options);
3403
3409
  if (!(typeof createImageBitmap === "undefined" || typeof OffscreenCanvas === "undefined")) {
3404
3410
  _context10.next = 1;
3405
3411
  break;
@@ -3465,7 +3471,7 @@ function _processFile() {
3465
3471
  return _regeneratorRuntime.wrap(function (_context11) {
3466
3472
  while (1) switch (_context11.prev = _context11.next) {
3467
3473
  case 0:
3468
- opts = _objectSpread$3(_objectSpread$3({}, DEFAULT_COMPRESS), compress);
3474
+ opts = _objectSpread$1(_objectSpread$1({}, DEFAULT_COMPRESS), compress);
3469
3475
  if (!(opts.enabled && isImage(fileName))) {
3470
3476
  _context11.next = 2;
3471
3477
  break;
@@ -3529,7 +3535,7 @@ function createOssClient() {
3529
3535
  var allowedExtensions = options.allowedExtensions;
3530
3536
  function mergeRetry(override) {
3531
3537
  if (!defaultRetry && !override) return void 0;
3532
- return _objectSpread$3(_objectSpread$3({}, defaultRetry), override);
3538
+ return _objectSpread$1(_objectSpread$1({}, defaultRetry), override);
3533
3539
  }
3534
3540
  function resolveCompress(override) {
3535
3541
  if (override === false) return {
@@ -3539,7 +3545,7 @@ function createOssClient() {
3539
3545
  enabled: false
3540
3546
  };
3541
3547
  var base = _typeof$1(defaultCompress) === "object" ? defaultCompress : {};
3542
- return override ? _objectSpread$3(_objectSpread$3({}, base), override) : Object.keys(base).length ? base : void 0;
3548
+ return override ? _objectSpread$1(_objectSpread$1({}, base), override) : Object.keys(base).length ? base : void 0;
3543
3549
  }
3544
3550
  function uploadOne(_x25, _x26, _x27, _x28) {
3545
3551
  return _uploadOne.apply(this, arguments);
@@ -3625,7 +3631,7 @@ function createOssClient() {
3625
3631
  var i = index++;
3626
3632
  var item = files[i];
3627
3633
  running++;
3628
- var fileOpts = _objectSpread$3({
3634
+ var fileOpts = _objectSpread$1({
3629
3635
  retry: opts === null || opts === void 0 ? void 0 : opts.retry,
3630
3636
  compress: opts === null || opts === void 0 ? void 0 : opts.compress
3631
3637
  }, item.options);
@@ -4041,12 +4047,12 @@ function _getSessionAdminRow() {
4041
4047
  }));
4042
4048
  return _getSessionAdminRow.apply(this, arguments);
4043
4049
  }
4044
- function isUserSessionAdmin(_x4, _x5, _x6) {
4045
- return _isUserSessionAdmin.apply(this, arguments);
4050
+ function getSessionAdminRowByEmail(_x4, _x5, _x6) {
4051
+ return _getSessionAdminRowByEmail.apply(this, arguments);
4046
4052
  }
4047
- function _isUserSessionAdmin() {
4048
- _isUserSessionAdmin = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(supabase, sessionId, userId) {
4049
- var row;
4053
+ function _getSessionAdminRowByEmail() {
4054
+ _getSessionAdminRowByEmail = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(supabase, sessionId, email) {
4055
+ var row, normalizedEmail, rowEmail;
4050
4056
  return _regeneratorRuntime.wrap(function (_context3) {
4051
4057
  while (1) switch (_context3.prev = _context3.next) {
4052
4058
  case 0:
@@ -4058,18 +4064,189 @@ function _isUserSessionAdmin() {
4058
4064
  _context3.next = 2;
4059
4065
  break;
4060
4066
  }
4061
- return _context3.abrupt("return", false);
4067
+ return _context3.abrupt("return", null);
4062
4068
  case 2:
4063
- return _context3.abrupt("return", row.user_id === userId);
4069
+ normalizedEmail = (email || "").trim().toLowerCase();
4070
+ rowEmail = (row.email || "").trim().toLowerCase();
4071
+ if (!(!normalizedEmail || rowEmail !== normalizedEmail)) {
4072
+ _context3.next = 3;
4073
+ break;
4074
+ }
4075
+ return _context3.abrupt("return", null);
4064
4076
  case 3:
4077
+ return _context3.abrupt("return", row);
4078
+ case 4:
4065
4079
  case "end":
4066
4080
  return _context3.stop();
4067
4081
  }
4068
4082
  }, _callee3);
4069
4083
  }));
4084
+ return _getSessionAdminRowByEmail.apply(this, arguments);
4085
+ }
4086
+ function isUserSessionAdmin(_x7, _x8, _x9) {
4087
+ return _isUserSessionAdmin.apply(this, arguments);
4088
+ }
4089
+ function _isUserSessionAdmin() {
4090
+ _isUserSessionAdmin = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(supabase, sessionId, userId) {
4091
+ var row;
4092
+ return _regeneratorRuntime.wrap(function (_context4) {
4093
+ while (1) switch (_context4.prev = _context4.next) {
4094
+ case 0:
4095
+ _context4.next = 1;
4096
+ return getSessionAdminRow(supabase, sessionId);
4097
+ case 1:
4098
+ row = _context4.sent;
4099
+ if (row) {
4100
+ _context4.next = 2;
4101
+ break;
4102
+ }
4103
+ return _context4.abrupt("return", false);
4104
+ case 2:
4105
+ return _context4.abrupt("return", row.user_id === userId);
4106
+ case 3:
4107
+ case "end":
4108
+ return _context4.stop();
4109
+ }
4110
+ }, _callee4);
4111
+ }));
4070
4112
  return _isUserSessionAdmin.apply(this, arguments);
4071
4113
  }
4072
4114
 
4115
+ var ACTION_LABELS = {
4116
+ create: "创建",
4117
+ read: "查询",
4118
+ update: "更新",
4119
+ "delete": "删除"
4120
+ };
4121
+ var TARGET_LABELS = {
4122
+ data: "数据",
4123
+ model: "模型"
4124
+ };
4125
+ function getWebhookUrls() {
4126
+ return feishuAlertConfig.crudErrorWebhookUrls.map(function (item) {
4127
+ return item.trim();
4128
+ }).filter(Boolean);
4129
+ }
4130
+ function getErrorMessage(error) {
4131
+ if (error instanceof Error) {
4132
+ return error.message;
4133
+ }
4134
+ return String(error);
4135
+ }
4136
+ function getErrorStack(error) {
4137
+ if (error instanceof Error) {
4138
+ return error.stack || "";
4139
+ }
4140
+ return "";
4141
+ }
4142
+ function buildRequestSummary(c) {
4143
+ var url = new URL(c.req.url);
4144
+ return ["method: ".concat(c.req.method), "path: ".concat(url.pathname), "query: ".concat(url.search || "-"), "userAgent: ".concat(c.req.header("user-agent") || "-")].join("\n");
4145
+ }
4146
+ function getSessionId(c) {
4147
+ return c.req.header("X-Session-Id") || c.req.header("x-session-id") || "-";
4148
+ }
4149
+ function buildAlertText(c, options) {
4150
+ var _options$modelId, _options$recordId;
4151
+ var actionLabel = ACTION_LABELS[options.action];
4152
+ var targetLabel = TARGET_LABELS[options.target];
4153
+ var lines = ["\u5305\u540D: @wecode-team/cms-supabase-api", "\u5BBF\u4E3B\u9879\u76EE\u6807\u8BC6(sessionId): ".concat(getSessionId(c)), "\u64CD\u4F5C\u5BF9\u8C61: ".concat(targetLabel), "\u64CD\u4F5C\u7C7B\u578B: ".concat(actionLabel), "\u6570\u636E\u8868\u540D: ".concat(options.tableName || "-"), "\u6A21\u578B ID: ".concat((_options$modelId = options.modelId) !== null && _options$modelId !== void 0 ? _options$modelId : "-"), "\u8BB0\u5F55 ID: ".concat((_options$recordId = options.recordId) !== null && _options$recordId !== void 0 ? _options$recordId : "-"), "\u65F6\u95F4: ".concat(new Date().toISOString()), "\u9519\u8BEF\u4FE1\u606F: ".concat(getErrorMessage(options.error)), "\u8BF7\u6C42\u4FE1\u606F:\n".concat(buildRequestSummary(c))];
4154
+ var stack = getErrorStack(options.error);
4155
+ if (stack) {
4156
+ lines.push("\u9519\u8BEF\u5806\u6808:\n".concat(stack));
4157
+ }
4158
+ return lines.join("\n\n");
4159
+ }
4160
+ function postWebhook(_x, _x2) {
4161
+ return _postWebhook.apply(this, arguments);
4162
+ }
4163
+ function _postWebhook() {
4164
+ _postWebhook = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(webhook, body) {
4165
+ var response;
4166
+ return _regeneratorRuntime.wrap(function (_context) {
4167
+ while (1) switch (_context.prev = _context.next) {
4168
+ case 0:
4169
+ _context.next = 1;
4170
+ return fetch(webhook, {
4171
+ method: "POST",
4172
+ headers: {
4173
+ "Content-Type": "application/json"
4174
+ },
4175
+ body: JSON.stringify(body)
4176
+ });
4177
+ case 1:
4178
+ response = _context.sent;
4179
+ if (response.ok) {
4180
+ _context.next = 2;
4181
+ break;
4182
+ }
4183
+ throw new Error("\u98DE\u4E66\u62A5\u8B66\u53D1\u9001\u5931\u8D25: ".concat(response.status, " ").concat(response.statusText));
4184
+ case 2:
4185
+ case "end":
4186
+ return _context.stop();
4187
+ }
4188
+ }, _callee);
4189
+ }));
4190
+ return _postWebhook.apply(this, arguments);
4191
+ }
4192
+ function notifyCmsCrudErrorToFeishu(_x3, _x4) {
4193
+ return _notifyCmsCrudErrorToFeishu.apply(this, arguments);
4194
+ }
4195
+ function _notifyCmsCrudErrorToFeishu() {
4196
+ _notifyCmsCrudErrorToFeishu = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(c, options) {
4197
+ var webhookUrls, body, results, failed;
4198
+ return _regeneratorRuntime.wrap(function (_context2) {
4199
+ while (1) switch (_context2.prev = _context2.next) {
4200
+ case 0:
4201
+ webhookUrls = getWebhookUrls();
4202
+ if (!(webhookUrls.length === 0)) {
4203
+ _context2.next = 1;
4204
+ break;
4205
+ }
4206
+ return _context2.abrupt("return");
4207
+ case 1:
4208
+ body = {
4209
+ msg_type: "post",
4210
+ content: {
4211
+ post: {
4212
+ zh_cn: {
4213
+ title: "[cms-supabase-api] ".concat(TARGET_LABELS[options.target]).concat(ACTION_LABELS[options.action], "\u5F02\u5E38"),
4214
+ content: [[{
4215
+ tag: "text",
4216
+ text: buildAlertText(c, options)
4217
+ }]]
4218
+ }
4219
+ }
4220
+ }
4221
+ };
4222
+ _context2.next = 2;
4223
+ return Promise.allSettled(webhookUrls.map(function (url) {
4224
+ return postWebhook(url, body);
4225
+ }));
4226
+ case 2:
4227
+ results = _context2.sent;
4228
+ failed = results.find(function (result) {
4229
+ return result.status === "rejected";
4230
+ });
4231
+ if (!((failed === null || failed === void 0 ? void 0 : failed.status) === "rejected")) {
4232
+ _context2.next = 3;
4233
+ break;
4234
+ }
4235
+ throw failed.reason;
4236
+ case 3:
4237
+ case "end":
4238
+ return _context2.stop();
4239
+ }
4240
+ }, _callee2);
4241
+ }));
4242
+ return _notifyCmsCrudErrorToFeishu.apply(this, arguments);
4243
+ }
4244
+ function reportCmsCrudErrorToFeishu(c, options) {
4245
+ void notifyCmsCrudErrorToFeishu(c, options)["catch"](function (feishuError) {
4246
+ console.error("飞书报警发送失败:", feishuError);
4247
+ });
4248
+ }
4249
+
4073
4250
  function _createForOfIteratorHelper$1(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray$1(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
4074
4251
  function _unsupportedIterableToArray$1(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray$1(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray$1(r, a) : void 0; } }
4075
4252
  function _arrayLikeToArray$1(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
@@ -4371,6 +4548,11 @@ function _createModel() {
4371
4548
  _context3.prev = 15;
4372
4549
  _t3 = _context3["catch"](0);
4373
4550
  console.error("创建模型失败:", _t3);
4551
+ reportCmsCrudErrorToFeishu(c, {
4552
+ action: "create",
4553
+ target: "model",
4554
+ error: _t3
4555
+ });
4374
4556
  _response9 = {
4375
4557
  success: false,
4376
4558
  message: "创建模型失败",
@@ -4462,6 +4644,11 @@ function _updateModel() {
4462
4644
  _context4.prev = 8;
4463
4645
  _t4 = _context4["catch"](0);
4464
4646
  console.error("更新模型失败:", _t4);
4647
+ reportCmsCrudErrorToFeishu(c, {
4648
+ action: "update",
4649
+ target: "model",
4650
+ error: _t4
4651
+ });
4465
4652
  _response11 = {
4466
4653
  success: false,
4467
4654
  message: "更新模型失败",
@@ -4543,6 +4730,11 @@ function _deleteModel() {
4543
4730
  _context5.prev = 8;
4544
4731
  _t5 = _context5["catch"](0);
4545
4732
  console.error("删除模型失败:", _t5);
4733
+ reportCmsCrudErrorToFeishu(c, {
4734
+ action: "delete",
4735
+ target: "model",
4736
+ error: _t5
4737
+ });
4546
4738
  _response15 = {
4547
4739
  success: false,
4548
4740
  message: "删除模型失败",
@@ -4604,8 +4796,8 @@ var _excluded = ["id", "created_at", "updated_at"],
4604
4796
  function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n2 = 0, F = function F() {}; return { s: F, n: function n() { return _n2 >= r.length ? { done: !0 } : { done: !1, value: r[_n2++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
4605
4797
  function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
4606
4798
  function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
4607
- function ownKeys$2(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
4608
- function _objectSpread$2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$2(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
4799
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
4800
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
4609
4801
  function normalizeJsonLikeFields(schemaFields, payload) {
4610
4802
  if (!schemaFields || schemaFields.length === 0) return payload;
4611
4803
  var jsonLikeFieldNames = new Set(schemaFields.filter(function (f) {
@@ -4614,7 +4806,7 @@ function normalizeJsonLikeFields(schemaFields, payload) {
4614
4806
  return f.name;
4615
4807
  }));
4616
4808
  if (jsonLikeFieldNames.size === 0) return payload;
4617
- var normalized = _objectSpread$2({}, payload);
4809
+ var normalized = _objectSpread({}, payload);
4618
4810
  for (var _i = 0, _Object$entries = Object.entries(payload); _i < _Object$entries.length; _i++) {
4619
4811
  var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
4620
4812
  key = _Object$entries$_i[0],
@@ -4909,7 +5101,7 @@ function _getTableData() {
4909
5101
  }
4910
5102
  // 找到所有文本类型的字段
4911
5103
  searchableFields = schemaFields.filter(function (field) {
4912
- return field.type === 'string' || field.type === 'text';
5104
+ return field.type === 'string' || field.type === 'text' || field.type === 'richText';
4913
5105
  }).map(function (field) {
4914
5106
  return field.name;
4915
5107
  });
@@ -4954,6 +5146,12 @@ function _getTableData() {
4954
5146
  _context.prev = 16;
4955
5147
  _t2 = _context["catch"](0);
4956
5148
  console.error("获取表数据失败:", _t2);
5149
+ reportCmsCrudErrorToFeishu(c, {
5150
+ action: "read",
5151
+ target: "data",
5152
+ tableName: tableName,
5153
+ error: _t2
5154
+ });
4957
5155
  _response3 = {
4958
5156
  success: false,
4959
5157
  message: "获取表数据失败",
@@ -5040,6 +5238,12 @@ function _createTableData() {
5040
5238
  _context2.prev = 8;
5041
5239
  _t4 = _context2["catch"](0);
5042
5240
  console.error("创建数据失败:", _t4);
5241
+ reportCmsCrudErrorToFeishu(c, {
5242
+ action: "create",
5243
+ target: "data",
5244
+ tableName: tableName,
5245
+ error: _t4
5246
+ });
5043
5247
  _response5 = {
5044
5248
  success: false,
5045
5249
  message: "创建数据失败",
@@ -5171,6 +5375,12 @@ function _updateTableData() {
5171
5375
  _context3.prev = 13;
5172
5376
  _t6 = _context3["catch"](0);
5173
5377
  console.error("更新数据失败:", _t6);
5378
+ reportCmsCrudErrorToFeishu(c, {
5379
+ action: "update",
5380
+ target: "data",
5381
+ tableName: tableName,
5382
+ error: _t6
5383
+ });
5174
5384
  _response1 = {
5175
5385
  success: false,
5176
5386
  message: "更新数据失败",
@@ -5254,6 +5464,12 @@ function _deleteTableData() {
5254
5464
  _context4.prev = 7;
5255
5465
  _t7 = _context4["catch"](0);
5256
5466
  console.error("删除数据失败:", _t7);
5467
+ reportCmsCrudErrorToFeishu(c, {
5468
+ action: "delete",
5469
+ target: "data",
5470
+ tableName: tableName,
5471
+ error: _t7
5472
+ });
5257
5473
  _response13 = {
5258
5474
  success: false,
5259
5475
  message: "删除数据失败",
@@ -5710,8 +5926,6 @@ var AuthUtils = /*#__PURE__*/function () {
5710
5926
  }]);
5711
5927
  }();
5712
5928
 
5713
- function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
5714
- function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
5715
5929
  function getRoleFromSupabaseUser$2(user) {
5716
5930
  var _user$app_metadata, _user$user_metadata;
5717
5931
  var appRole = user === null || user === void 0 || (_user$app_metadata = user.app_metadata) === null || _user$app_metadata === void 0 ? void 0 : _user$app_metadata.role;
@@ -5721,10 +5935,46 @@ function getRoleFromSupabaseUser$2(user) {
5721
5935
  function getAdminRegistrySetupSQL() {
5722
5936
  return "-- Create admin registry table (run in Supabase SQL editor)\nCREATE TABLE IF NOT EXISTS \"_cms_admin_registry\" (\n session_id TEXT PRIMARY KEY,\n user_id UUID NOT NULL,\n email TEXT,\n created_at TIMESTAMPTZ DEFAULT NOW()\n);\n\nALTER TABLE \"_cms_admin_registry\" ENABLE ROW LEVEL SECURITY;\nDROP POLICY IF EXISTS \"Allow all operations\" ON \"_cms_admin_registry\";\nCREATE POLICY \"Allow all operations\" ON \"_cms_admin_registry\"\n FOR ALL USING (true) WITH CHECK (true);";
5723
5937
  }
5724
- function isSupabaseUserAlreadyExistsError(error) {
5725
- var msg = String((error === null || error === void 0 ? void 0 : error.message) || "").toLowerCase();
5726
- // 兼容不同 Supabase 文案
5727
- return msg.includes("already registered") || msg.includes("already exists") || msg.includes("user already") || msg.includes("email address") && msg.includes("already");
5938
+ function isEmailLike(value) {
5939
+ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim());
5940
+ }
5941
+ var PASSWORD_RESET_MESSAGES = {
5942
+ "zh-CN": {
5943
+ emailRequired: "邮箱不能为空",
5944
+ emailInvalid: "请输入邮箱格式的用户名",
5945
+ codeRequired: "验证码不能为空",
5946
+ passwordTooShort: "新密码至少需要 6 位",
5947
+ codeSent: "如果账号存在,验证码已发送",
5948
+ codeSendFailed: "发送重置密码验证码失败",
5949
+ codeSendRetry: "验证码发送失败,请稍后重试",
5950
+ userNotFound: "验证码无效或账号不存在",
5951
+ codeInvalidOrExpired: "验证码无效或已过期",
5952
+ resetSuccess: "密码已重置,请重新登录",
5953
+ resetFailed: "重置密码失败"
5954
+ },
5955
+ "en-US": {
5956
+ emailRequired: "Email is required",
5957
+ emailInvalid: "Please enter a valid email address",
5958
+ codeRequired: "Verification code is required",
5959
+ passwordTooShort: "New password must be at least 6 characters",
5960
+ codeSent: "If the account exists, a verification code has been sent",
5961
+ codeSendFailed: "Failed to send password reset code",
5962
+ codeSendRetry: "Failed to send verification code. Please try again later",
5963
+ userNotFound: "Invalid code or account not found",
5964
+ codeInvalidOrExpired: "Invalid or expired verification code",
5965
+ resetSuccess: "Password has been reset. Please log in again",
5966
+ resetFailed: "Failed to reset password"
5967
+ }
5968
+ };
5969
+ function getLocaleFromRequest(c) {
5970
+ var raw = (c.req.header("accept-language") || c.req.header("Accept-Language") || "").toLowerCase();
5971
+ if (raw.includes("en")) {
5972
+ return "en-US";
5973
+ }
5974
+ return "zh-CN";
5975
+ }
5976
+ function getPasswordResetMessages(c) {
5977
+ return PASSWORD_RESET_MESSAGES[getLocaleFromRequest(c)];
5728
5978
  }
5729
5979
  function toSupabaseEmail(account, sessionId) {
5730
5980
  // 简单规则:`{session_id}_{邮箱前缀}@{邮箱后缀}`
@@ -5736,168 +5986,235 @@ function toSupabaseEmail(account, sessionId) {
5736
5986
  var sid = normalizeSessionId(sessionId);
5737
5987
  return "".concat(sid, "_").concat(localPart, "@").concat(domain);
5738
5988
  }
5739
- function buildAdminMetadata(existingMetadata, sessionId, account) {
5740
- return _objectSpread$1(_objectSpread$1({}, existingMetadata || {}), {}, {
5741
- role: "admin",
5742
- session_id: normalizeSessionId(sessionId),
5743
- original_username: account
5744
- });
5989
+ function isEmailVerifyError(error) {
5990
+ var name = String((error === null || error === void 0 ? void 0 : error.name) || "");
5991
+ return name === "EmailVerifyError";
5745
5992
  }
5746
- function findAuthUserByEmail(_x, _x2) {
5747
- return _findAuthUserByEmail.apply(this, arguments);
5993
+ // POST - 发送重置密码验证码
5994
+ function forgotPassword(_x, _x2) {
5995
+ return _forgotPassword.apply(this, arguments);
5748
5996
  }
5749
- function _findAuthUserByEmail() {
5750
- _findAuthUserByEmail = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(supabase, email) {
5751
- var normalizedEmail, page, _yield$supabase$auth$2, data, error, users, matchedUser;
5997
+ // POST - 通过邮箱验证码重置密码
5998
+ function _forgotPassword() {
5999
+ _forgotPassword = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(c, tableName) {
6000
+ var _body$username, i18n, body, account, supabase, sessionId, adminRow, _i18n, _t3;
5752
6001
  return _regeneratorRuntime.wrap(function (_context2) {
5753
6002
  while (1) switch (_context2.prev = _context2.next) {
5754
6003
  case 0:
5755
- normalizedEmail = email.trim().toLowerCase();
5756
- page = 1;
6004
+ _context2.prev = 0;
6005
+ i18n = getPasswordResetMessages(c);
6006
+ _context2.next = 1;
6007
+ return c.req.json();
5757
6008
  case 1:
5758
- if (!(page <= 10)) {
5759
- _context2.next = 6;
6009
+ body = _context2.sent;
6010
+ account = (_body$username = body.username) === null || _body$username === void 0 ? void 0 : _body$username.trim();
6011
+ if (account) {
6012
+ _context2.next = 2;
5760
6013
  break;
5761
6014
  }
5762
- _context2.next = 2;
5763
- return supabase.auth.admin.listUsers({
5764
- page: page,
5765
- perPage: 200
5766
- });
6015
+ return _context2.abrupt("return", c.json({
6016
+ success: false,
6017
+ message: i18n.emailRequired
6018
+ }, 200));
5767
6019
  case 2:
5768
- _yield$supabase$auth$2 = _context2.sent;
5769
- data = _yield$supabase$auth$2.data;
5770
- error = _yield$supabase$auth$2.error;
5771
- if (!error) {
6020
+ if (isEmailLike(account)) {
5772
6021
  _context2.next = 3;
5773
6022
  break;
5774
6023
  }
5775
- throw error;
6024
+ return _context2.abrupt("return", c.json({
6025
+ success: false,
6026
+ message: i18n.emailInvalid
6027
+ }, 200));
5776
6028
  case 3:
5777
- users = (data === null || data === void 0 ? void 0 : data.users) || [];
5778
- matchedUser = users.find(function (user) {
5779
- var _user$email;
5780
- return ((_user$email = user.email) === null || _user$email === void 0 ? void 0 : _user$email.trim().toLowerCase()) === normalizedEmail;
5781
- });
5782
- if (!matchedUser) {
5783
- _context2.next = 4;
5784
- break;
5785
- }
5786
- return _context2.abrupt("return", matchedUser);
6029
+ supabase = getSupabase();
6030
+ sessionId = extractSessionIdFromAuthTableName(tableName);
6031
+ _context2.next = 4;
6032
+ return getSessionAdminRowByEmail(supabase, sessionId, account);
5787
6033
  case 4:
5788
- if (!(users.length < 200)) {
6034
+ adminRow = _context2.sent;
6035
+ if (adminRow !== null && adminRow !== void 0 && adminRow.user_id) {
5789
6036
  _context2.next = 5;
5790
6037
  break;
5791
6038
  }
5792
- return _context2.abrupt("return", null);
6039
+ return _context2.abrupt("return", c.json({
6040
+ success: true,
6041
+ message: i18n.codeSent
6042
+ }, 200));
5793
6043
  case 5:
5794
- page += 1;
5795
- _context2.next = 1;
5796
- break;
6044
+ _context2.next = 6;
6045
+ return emailVerify.sendCode(account);
5797
6046
  case 6:
5798
- return _context2.abrupt("return", null);
6047
+ return _context2.abrupt("return", c.json({
6048
+ success: true,
6049
+ message: i18n.codeSent
6050
+ }, 200));
5799
6051
  case 7:
6052
+ _context2.prev = 7;
6053
+ _t3 = _context2["catch"](0);
6054
+ console.error("发送重置密码验证码失败:", _t3);
6055
+ _i18n = getPasswordResetMessages(c);
6056
+ return _context2.abrupt("return", c.json({
6057
+ success: false,
6058
+ message: isEmailVerifyError(_t3) ? _i18n.codeSendRetry : _i18n.codeSendFailed,
6059
+ error: _t3.message
6060
+ }, 500));
6061
+ case 8:
5800
6062
  case "end":
5801
6063
  return _context2.stop();
5802
6064
  }
5803
- }, _callee2);
6065
+ }, _callee2, null, [[0, 7]]);
5804
6066
  }));
5805
- return _findAuthUserByEmail.apply(this, arguments);
6067
+ return _forgotPassword.apply(this, arguments);
5806
6068
  }
5807
- function insertAdminRegistryRow(_x3, _x4, _x5, _x6) {
5808
- return _insertAdminRegistryRow.apply(this, arguments);
6069
+ function resetPassword(_x3, _x4) {
6070
+ return _resetPassword.apply(this, arguments);
5809
6071
  }
5810
- function _insertAdminRegistryRow() {
5811
- _insertAdminRegistryRow = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(supabase, sessionId, userId, account) {
6072
+ function _resetPassword() {
6073
+ _resetPassword = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(c, tableName) {
6074
+ var _body$username2, _body$code, i18n, body, account, code, password, supabase, sessionId, adminRow, verifyResult, _yield$supabase$auth$2, updateError, _i18n2, _t4;
5812
6075
  return _regeneratorRuntime.wrap(function (_context3) {
5813
6076
  while (1) switch (_context3.prev = _context3.next) {
5814
6077
  case 0:
6078
+ _context3.prev = 0;
6079
+ i18n = getPasswordResetMessages(c);
5815
6080
  _context3.next = 1;
5816
- return supabase.from("_cms_admin_registry").insert({
5817
- session_id: normalizeSessionId(sessionId),
5818
- user_id: userId,
5819
- email: account
5820
- });
5821
- case 1:
5822
- return _context3.abrupt("return", _context3.sent);
5823
- case 2:
5824
- case "end":
5825
- return _context3.stop();
5826
- }
5827
- }, _callee3);
5828
- }));
5829
- return _insertAdminRegistryRow.apply(this, arguments);
5830
- }
5831
- function promoteExistingUserToSessionAdmin(_x7, _x8, _x9, _x0) {
5832
- return _promoteExistingUserToSessionAdmin.apply(this, arguments);
5833
- }
5834
- function _promoteExistingUserToSessionAdmin() {
5835
- _promoteExistingUserToSessionAdmin = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(supabase, email, sessionId, account) {
5836
- var existingUser, _yield$supabase$auth$3, updatedData, updateError, insertRes;
5837
- return _regeneratorRuntime.wrap(function (_context4) {
5838
- while (1) switch (_context4.prev = _context4.next) {
5839
- case 0:
5840
- _context4.next = 1;
5841
- return findAuthUserByEmail(supabase, email);
6081
+ return c.req.json();
5842
6082
  case 1:
5843
- existingUser = _context4.sent;
5844
- if (existingUser) {
5845
- _context4.next = 2;
6083
+ body = _context3.sent;
6084
+ account = (_body$username2 = body.username) === null || _body$username2 === void 0 ? void 0 : _body$username2.trim();
6085
+ code = (_body$code = body.code) === null || _body$code === void 0 ? void 0 : _body$code.trim();
6086
+ password = body.password;
6087
+ if (account) {
6088
+ _context3.next = 2;
5846
6089
  break;
5847
6090
  }
5848
- return _context4.abrupt("return", {
6091
+ return _context3.abrupt("return", c.json({
5849
6092
  success: false,
5850
- message: "用户名已存在,但未能找到对应用户"
5851
- });
6093
+ message: i18n.emailRequired
6094
+ }, 200));
5852
6095
  case 2:
5853
- _context4.next = 3;
5854
- return supabase.auth.admin.updateUserById(existingUser.id, {
5855
- app_metadata: buildAdminMetadata(existingUser.app_metadata, sessionId, account),
5856
- user_metadata: buildAdminMetadata(existingUser.user_metadata, sessionId, account)
5857
- });
6096
+ if (isEmailLike(account)) {
6097
+ _context3.next = 3;
6098
+ break;
6099
+ }
6100
+ return _context3.abrupt("return", c.json({
6101
+ success: false,
6102
+ message: i18n.emailInvalid
6103
+ }, 200));
5858
6104
  case 3:
5859
- _yield$supabase$auth$3 = _context4.sent;
5860
- updatedData = _yield$supabase$auth$3.data;
5861
- updateError = _yield$supabase$auth$3.error;
5862
- if (!(updateError || !(updatedData !== null && updatedData !== void 0 && updatedData.user))) {
5863
- _context4.next = 4;
6105
+ if (code) {
6106
+ _context3.next = 4;
5864
6107
  break;
5865
6108
  }
5866
- return _context4.abrupt("return", {
6109
+ return _context3.abrupt("return", c.json({
5867
6110
  success: false,
5868
- message: (updateError === null || updateError === void 0 ? void 0 : updateError.message) || "管理员账号升级失败"
5869
- });
6111
+ message: i18n.codeRequired
6112
+ }, 200));
5870
6113
  case 4:
5871
- _context4.next = 5;
5872
- return insertAdminRegistryRow(supabase, sessionId, updatedData.user.id, account);
6114
+ if (!(!password || password.length < 6)) {
6115
+ _context3.next = 5;
6116
+ break;
6117
+ }
6118
+ return _context3.abrupt("return", c.json({
6119
+ success: false,
6120
+ message: i18n.passwordTooShort
6121
+ }, 200));
5873
6122
  case 5:
5874
- insertRes = _context4.sent;
5875
- if (!insertRes.error) {
5876
- _context4.next = 6;
6123
+ supabase = getSupabase();
6124
+ sessionId = extractSessionIdFromAuthTableName(tableName);
6125
+ _context3.next = 6;
6126
+ return getSessionAdminRowByEmail(supabase, sessionId, account);
6127
+ case 6:
6128
+ adminRow = _context3.sent;
6129
+ if (adminRow !== null && adminRow !== void 0 && adminRow.user_id) {
6130
+ _context3.next = 7;
5877
6131
  break;
5878
6132
  }
5879
- return _context4.abrupt("return", {
6133
+ return _context3.abrupt("return", c.json({
5880
6134
  success: false,
5881
- message: "管理员已被创建,请使用已有账号登录"
6135
+ message: i18n.userNotFound
6136
+ }, 200));
6137
+ case 7:
6138
+ _context3.next = 8;
6139
+ return emailVerify.verifyCode(account, code);
6140
+ case 8:
6141
+ verifyResult = _context3.sent;
6142
+ if (verifyResult !== null && verifyResult !== void 0 && verifyResult.verified) {
6143
+ _context3.next = 9;
6144
+ break;
6145
+ }
6146
+ return _context3.abrupt("return", c.json({
6147
+ success: false,
6148
+ message: i18n.codeInvalidOrExpired
6149
+ }, 200));
6150
+ case 9:
6151
+ _context3.next = 10;
6152
+ return supabase.auth.admin.updateUserById(adminRow.user_id, {
6153
+ password: password
5882
6154
  });
5883
- case 6:
5884
- return _context4.abrupt("return", {
6155
+ case 10:
6156
+ _yield$supabase$auth$2 = _context3.sent;
6157
+ updateError = _yield$supabase$auth$2.error;
6158
+ if (!updateError) {
6159
+ _context3.next = 11;
6160
+ break;
6161
+ }
6162
+ return _context3.abrupt("return", c.json({
6163
+ success: false,
6164
+ message: updateError.message || i18n.resetFailed
6165
+ }, 200));
6166
+ case 11:
6167
+ return _context3.abrupt("return", c.json({
5885
6168
  success: true,
5886
- user: updatedData.user
6169
+ message: i18n.resetSuccess
6170
+ }, 200));
6171
+ case 12:
6172
+ _context3.prev = 12;
6173
+ _t4 = _context3["catch"](0);
6174
+ console.error("重置密码失败:", _t4);
6175
+ _i18n2 = getPasswordResetMessages(c);
6176
+ return _context3.abrupt("return", c.json({
6177
+ success: false,
6178
+ message: _i18n2.resetFailed,
6179
+ error: _t4.message
6180
+ }, 500));
6181
+ case 13:
6182
+ case "end":
6183
+ return _context3.stop();
6184
+ }
6185
+ }, _callee3, null, [[0, 12]]);
6186
+ }));
6187
+ return _resetPassword.apply(this, arguments);
6188
+ }
6189
+ function insertAdminRegistryRow(_x5, _x6, _x7, _x8) {
6190
+ return _insertAdminRegistryRow.apply(this, arguments);
6191
+ }
6192
+ function _insertAdminRegistryRow() {
6193
+ _insertAdminRegistryRow = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(supabase, sessionId, userId, account) {
6194
+ return _regeneratorRuntime.wrap(function (_context4) {
6195
+ while (1) switch (_context4.prev = _context4.next) {
6196
+ case 0:
6197
+ _context4.next = 1;
6198
+ return supabase.from("_cms_admin_registry").insert({
6199
+ session_id: normalizeSessionId(sessionId),
6200
+ user_id: userId,
6201
+ email: account
5887
6202
  });
5888
- case 7:
6203
+ case 1:
6204
+ return _context4.abrupt("return", _context4.sent);
6205
+ case 2:
5889
6206
  case "end":
5890
6207
  return _context4.stop();
5891
6208
  }
5892
6209
  }, _callee4);
5893
6210
  }));
5894
- return _promoteExistingUserToSessionAdmin.apply(this, arguments);
6211
+ return _insertAdminRegistryRow.apply(this, arguments);
5895
6212
  }
5896
6213
  function getUserSessionId(user) {
5897
6214
  var _user$user_metadata2;
5898
6215
  return normalizeSessionId(user === null || user === void 0 || (_user$user_metadata2 = user.user_metadata) === null || _user$user_metadata2 === void 0 ? void 0 : _user$user_metadata2.session_id);
5899
6216
  }
5900
- function getEffectiveRoleForSession(_x1, _x10) {
6217
+ function getEffectiveRoleForSession(_x9, _x0) {
5901
6218
  return _getEffectiveRoleForSession.apply(this, arguments);
5902
6219
  } // POST - 用户登录
5903
6220
  function _getEffectiveRoleForSession() {
@@ -5934,13 +6251,13 @@ function _getEffectiveRoleForSession() {
5934
6251
  }));
5935
6252
  return _getEffectiveRoleForSession.apply(this, arguments);
5936
6253
  }
5937
- function login(_x11, _x12) {
6254
+ function login(_x1, _x10) {
5938
6255
  return _login.apply(this, arguments);
5939
6256
  }
5940
6257
  // GET - 是否允许注册(首次进入需要创建管理员账号)
5941
6258
  function _login() {
5942
6259
  _login = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee6(c, tableName) {
5943
- var _data$session, body, username, password, supabase, sessionId, email, _yield$supabase$auth$4, data, error, token, user, role, _t3;
6260
+ var _data$session, body, username, password, supabase, sessionId, email, _yield$supabase$auth$3, data, error, token, user, role, _t5;
5944
6261
  return _regeneratorRuntime.wrap(function (_context6) {
5945
6262
  while (1) switch (_context6.prev = _context6.next) {
5946
6263
  case 0:
@@ -5978,9 +6295,9 @@ function _login() {
5978
6295
  password: password
5979
6296
  });
5980
6297
  case 4:
5981
- _yield$supabase$auth$4 = _context6.sent;
5982
- data = _yield$supabase$auth$4.data;
5983
- error = _yield$supabase$auth$4.error;
6298
+ _yield$supabase$auth$3 = _context6.sent;
6299
+ data = _yield$supabase$auth$3.data;
6300
+ error = _yield$supabase$auth$3.error;
5984
6301
  if (!(error || !(data !== null && data !== void 0 && (_data$session = data.session) !== null && _data$session !== void 0 && _data$session.access_token) || !(data !== null && data !== void 0 && data.user))) {
5985
6302
  _context6.next = 5;
5986
6303
  break;
@@ -6014,12 +6331,12 @@ function _login() {
6014
6331
  }, 200));
6015
6332
  case 8:
6016
6333
  _context6.prev = 8;
6017
- _t3 = _context6["catch"](0);
6018
- console.error("登录失败:", _t3);
6334
+ _t5 = _context6["catch"](0);
6335
+ console.error("登录失败:", _t5);
6019
6336
  return _context6.abrupt("return", c.json({
6020
6337
  success: false,
6021
6338
  message: "登录失败",
6022
- error: _t3.message
6339
+ error: _t5.message
6023
6340
  }, 500));
6024
6341
  case 9:
6025
6342
  case "end":
@@ -6029,13 +6346,13 @@ function _login() {
6029
6346
  }));
6030
6347
  return _login.apply(this, arguments);
6031
6348
  }
6032
- function signupStatus(_x13, _x14) {
6349
+ function signupStatus(_x11, _x12) {
6033
6350
  return _signupStatus.apply(this, arguments);
6034
6351
  }
6035
6352
  // POST - 首次注册管理员(每个 session_id 只允许一个)
6036
6353
  function _signupStatus() {
6037
6354
  _signupStatus = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee7(c, tableName) {
6038
- var supabase, sessionId, ok, row, data, _t4;
6355
+ var supabase, sessionId, ok, row, data, _t6;
6039
6356
  return _regeneratorRuntime.wrap(function (_context7) {
6040
6357
  while (1) switch (_context7.prev = _context7.next) {
6041
6358
  case 0:
@@ -6073,12 +6390,12 @@ function _signupStatus() {
6073
6390
  }, 200));
6074
6391
  case 4:
6075
6392
  _context7.prev = 4;
6076
- _t4 = _context7["catch"](0);
6077
- console.error("获取注册状态失败:", _t4);
6393
+ _t6 = _context7["catch"](0);
6394
+ console.error("获取注册状态失败:", _t6);
6078
6395
  return _context7.abrupt("return", c.json({
6079
6396
  success: false,
6080
6397
  message: "获取注册状态失败",
6081
- error: _t4.message
6398
+ error: _t6.message
6082
6399
  }, 500));
6083
6400
  case 5:
6084
6401
  case "end":
@@ -6088,13 +6405,13 @@ function _signupStatus() {
6088
6405
  }));
6089
6406
  return _signupStatus.apply(this, arguments);
6090
6407
  }
6091
- function signup(_x15, _x16) {
6408
+ function signup(_x13, _x14) {
6092
6409
  return _signup.apply(this, arguments);
6093
6410
  }
6094
6411
  // POST - 验证token
6095
6412
  function _signup() {
6096
6413
  _signup = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee8(c, tableName) {
6097
- var _body$username, _data$session2, body, account, password, supabase, sessionId, email, ok, existing, _yield$supabase$auth$5, data, error, promoted, insertRes, token, user, role, _t5;
6414
+ var _body$username3, _data$session2, body, account, password, supabase, sessionId, email, ok, existing, _yield$supabase$auth$4, data, error, insertRes, token, user, role, _t7;
6098
6415
  return _regeneratorRuntime.wrap(function (_context8) {
6099
6416
  while (1) switch (_context8.prev = _context8.next) {
6100
6417
  case 0:
@@ -6103,7 +6420,7 @@ function _signup() {
6103
6420
  return c.req.json();
6104
6421
  case 1:
6105
6422
  body = _context8.sent;
6106
- account = (_body$username = body.username) === null || _body$username === void 0 ? void 0 : _body$username.trim();
6423
+ account = (_body$username3 = body.username) === null || _body$username3 === void 0 ? void 0 : _body$username3.trim();
6107
6424
  password = body.password;
6108
6425
  if (!(!account || !password)) {
6109
6426
  _context8.next = 2;
@@ -6169,67 +6486,61 @@ function _signup() {
6169
6486
  }
6170
6487
  });
6171
6488
  case 8:
6172
- _yield$supabase$auth$5 = _context8.sent;
6173
- data = _yield$supabase$auth$5.data;
6174
- error = _yield$supabase$auth$5.error;
6489
+ _yield$supabase$auth$4 = _context8.sent;
6490
+ data = _yield$supabase$auth$4.data;
6491
+ error = _yield$supabase$auth$4.error;
6175
6492
  if (!(error || !(data !== null && data !== void 0 && data.user))) {
6176
- _context8.next = 12;
6177
- break;
6178
- }
6179
- if (!isSupabaseUserAlreadyExistsError(error)) {
6180
- _context8.next = 11;
6181
- break;
6182
- }
6183
- _context8.next = 9;
6184
- return promoteExistingUserToSessionAdmin(supabase, email, sessionId, account);
6185
- case 9:
6186
- promoted = _context8.sent;
6187
- if (promoted.success) {
6188
- _context8.next = 10;
6493
+ _context8.next = 9;
6189
6494
  break;
6190
6495
  }
6191
- return _context8.abrupt("return", c.json({
6192
- success: false,
6193
- message: promoted.message
6194
- }, 200));
6195
- case 10:
6196
- return _context8.abrupt("return", c.json({
6197
- success: true,
6198
- message: "管理员账号已启用,请登录"
6199
- }, 200));
6200
- case 11:
6496
+ console.log("注册失败:", error);
6497
+ // if (isSupabaseUserAlreadyExistsError(error)) {
6498
+ // const promoted = await promoteExistingUserToSessionAdmin(
6499
+ // supabase,
6500
+ // email,
6501
+ // sessionId,
6502
+ // account,
6503
+ // )
6504
+ // if (!promoted.success) {
6505
+ // return c.json({ success: false, message: promoted.message } as ApiResponse, 200)
6506
+ // }
6507
+ // return c.json(
6508
+ // { success: true, message: "管理员账号已启用,请登录" } as ApiResponse,
6509
+ // 200
6510
+ // )
6511
+ // }
6201
6512
  return _context8.abrupt("return", c.json({
6202
6513
  success: false,
6203
6514
  message: (error === null || error === void 0 ? void 0 : error.message) || "注册失败"
6204
6515
  }, 200));
6205
- case 12:
6516
+ case 9:
6206
6517
  if ((_data$session2 = data.session) !== null && _data$session2 !== void 0 && _data$session2.access_token) {
6207
- _context8.next = 13;
6518
+ _context8.next = 10;
6208
6519
  break;
6209
6520
  }
6210
6521
  return _context8.abrupt("return", c.json({
6211
6522
  success: true,
6212
6523
  message: "注册成功,请完成邮箱验证后登录"
6213
6524
  }, 200));
6214
- case 13:
6215
- _context8.next = 14;
6525
+ case 10:
6526
+ _context8.next = 11;
6216
6527
  return insertAdminRegistryRow(supabase, sessionId, data.user.id, account);
6217
- case 14:
6528
+ case 11:
6218
6529
  insertRes = _context8.sent;
6219
6530
  if (!insertRes.error) {
6220
- _context8.next = 15;
6531
+ _context8.next = 12;
6221
6532
  break;
6222
6533
  }
6223
6534
  return _context8.abrupt("return", c.json({
6224
6535
  success: false,
6225
6536
  message: "管理员已被创建,请使用已有账号登录"
6226
6537
  }, 200));
6227
- case 15:
6538
+ case 12:
6228
6539
  token = data.session.access_token;
6229
6540
  user = data.user;
6230
- _context8.next = 16;
6541
+ _context8.next = 13;
6231
6542
  return getEffectiveRoleForSession(user, sessionId);
6232
- case 16:
6543
+ case 13:
6233
6544
  role = _context8.sent;
6234
6545
  return _context8.abrupt("return", c.json({
6235
6546
  success: true,
@@ -6244,30 +6555,30 @@ function _signup() {
6244
6555
  }
6245
6556
  }
6246
6557
  }, 200));
6247
- case 17:
6248
- _context8.prev = 17;
6249
- _t5 = _context8["catch"](0);
6250
- console.error("注册失败:", _t5);
6558
+ case 14:
6559
+ _context8.prev = 14;
6560
+ _t7 = _context8["catch"](0);
6561
+ console.error("注册失败:", _t7);
6251
6562
  return _context8.abrupt("return", c.json({
6252
6563
  success: false,
6253
6564
  message: "注册失败",
6254
- error: _t5.message
6565
+ error: _t7.message
6255
6566
  }, 500));
6256
- case 18:
6567
+ case 15:
6257
6568
  case "end":
6258
6569
  return _context8.stop();
6259
6570
  }
6260
- }, _callee8, null, [[0, 17]]);
6571
+ }, _callee8, null, [[0, 14]]);
6261
6572
  }));
6262
6573
  return _signup.apply(this, arguments);
6263
6574
  }
6264
- function verifyAuth(_x17, _x18) {
6575
+ function verifyAuth(_x15, _x16) {
6265
6576
  return _verifyAuth.apply(this, arguments);
6266
6577
  }
6267
6578
  // GET - 获取当前用户信息
6268
6579
  function _verifyAuth() {
6269
6580
  _verifyAuth = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee9(c, tableName) {
6270
- var authHeader, token, supabase, _yield$supabase$auth$6, data, error, sessionId, role, decoded, message, responseMessage, _t6, _t7;
6581
+ var authHeader, token, supabase, _yield$supabase$auth$5, data, error, sessionId, role, decoded, message, responseMessage, _t8, _t9;
6271
6582
  return _regeneratorRuntime.wrap(function (_context9) {
6272
6583
  while (1) switch (_context9.prev = _context9.next) {
6273
6584
  case 0:
@@ -6288,9 +6599,9 @@ function _verifyAuth() {
6288
6599
  _context9.next = 2;
6289
6600
  return supabase.auth.getUser(token);
6290
6601
  case 2:
6291
- _yield$supabase$auth$6 = _context9.sent;
6292
- data = _yield$supabase$auth$6.data;
6293
- error = _yield$supabase$auth$6.error;
6602
+ _yield$supabase$auth$5 = _context9.sent;
6603
+ data = _yield$supabase$auth$5.data;
6604
+ error = _yield$supabase$auth$5.error;
6294
6605
  if (!(error || !(data !== null && data !== void 0 && data.user))) {
6295
6606
  _context9.next = 3;
6296
6607
  break;
@@ -6317,8 +6628,8 @@ function _verifyAuth() {
6317
6628
  }));
6318
6629
  case 6:
6319
6630
  _context9.prev = 6;
6320
- _t6 = _context9["catch"](1);
6321
- message = _t6.message;
6631
+ _t8 = _context9["catch"](1);
6632
+ message = _t8.message;
6322
6633
  responseMessage = message === 'TOKEN_EXPIRED' ? "登录已过期,请重新登录" : "认证信息无效";
6323
6634
  return _context9.abrupt("return", c.json({
6324
6635
  success: false,
@@ -6326,12 +6637,12 @@ function _verifyAuth() {
6326
6637
  }, 200));
6327
6638
  case 7:
6328
6639
  _context9.prev = 7;
6329
- _t7 = _context9["catch"](0);
6330
- console.error("验证认证失败:", _t7);
6640
+ _t9 = _context9["catch"](0);
6641
+ console.error("验证认证失败:", _t9);
6331
6642
  return _context9.abrupt("return", c.json({
6332
6643
  success: false,
6333
6644
  message: "验证认证失败",
6334
- error: _t7.message
6645
+ error: _t9.message
6335
6646
  }, 500));
6336
6647
  case 8:
6337
6648
  case "end":
@@ -6341,13 +6652,13 @@ function _verifyAuth() {
6341
6652
  }));
6342
6653
  return _verifyAuth.apply(this, arguments);
6343
6654
  }
6344
- function getCurrentUser(_x19, _x20) {
6655
+ function getCurrentUser(_x17, _x18) {
6345
6656
  return _getCurrentUser.apply(this, arguments);
6346
6657
  }
6347
6658
  // 中间件:验证 Supabase JWT token
6348
6659
  function _getCurrentUser() {
6349
6660
  _getCurrentUser = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee0(c, tableName) {
6350
- var authHeader, token, supabase, _yield$supabase$auth$7, data, error, user, sessionId, role, _t8;
6661
+ var authHeader, token, supabase, _yield$supabase$auth$6, data, error, user, sessionId, role, _t0;
6351
6662
  return _regeneratorRuntime.wrap(function (_context0) {
6352
6663
  while (1) switch (_context0.prev = _context0.next) {
6353
6664
  case 0:
@@ -6367,9 +6678,9 @@ function _getCurrentUser() {
6367
6678
  _context0.next = 2;
6368
6679
  return supabase.auth.getUser(token);
6369
6680
  case 2:
6370
- _yield$supabase$auth$7 = _context0.sent;
6371
- data = _yield$supabase$auth$7.data;
6372
- error = _yield$supabase$auth$7.error;
6681
+ _yield$supabase$auth$6 = _context0.sent;
6682
+ data = _yield$supabase$auth$6.data;
6683
+ error = _yield$supabase$auth$6.error;
6373
6684
  if (!(error || !(data !== null && data !== void 0 && data.user))) {
6374
6685
  _context0.next = 3;
6375
6686
  break;
@@ -6402,12 +6713,12 @@ function _getCurrentUser() {
6402
6713
  }, 200));
6403
6714
  case 6:
6404
6715
  _context0.prev = 6;
6405
- _t8 = _context0["catch"](0);
6406
- console.error("获取用户信息失败:", _t8);
6716
+ _t0 = _context0["catch"](0);
6717
+ console.error("获取用户信息失败:", _t0);
6407
6718
  return _context0.abrupt("return", c.json({
6408
6719
  success: false,
6409
6720
  message: "获取用户信息失败",
6410
- error: _t8.message
6721
+ error: _t0.message
6411
6722
  }, 500));
6412
6723
  case 7:
6413
6724
  case "end":
@@ -6487,7 +6798,7 @@ function requireAuth(handler) {
6487
6798
  }
6488
6799
  }, _callee, null, [[0, 5], [1, 4]]);
6489
6800
  }));
6490
- return function (_x21) {
6801
+ return function (_x19) {
6491
6802
  return _ref.apply(this, arguments);
6492
6803
  };
6493
6804
  }();
@@ -6540,7 +6851,7 @@ function _resolveUploadMaxSize() {
6540
6851
  return _resolveUploadMaxSize.apply(this, arguments);
6541
6852
  }
6542
6853
  function readSessionId(c) {
6543
- return c.req.header("X-Session-Id") || c.req.header("x-session-id") || '';
6854
+ return normalizeSessionId(c.req.header("X-Session-Id") || c.req.header("x-session-id")) || '';
6544
6855
  }
6545
6856
  function uploadToOss(_x3) {
6546
6857
  return _uploadToOss.apply(this, arguments);
@@ -6619,225 +6930,6 @@ function _uploadToOss() {
6619
6930
  return _uploadToOss.apply(this, arguments);
6620
6931
  }
6621
6932
 
6622
- function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
6623
- function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
6624
- var CONFIG_NAMESPACE_RE = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;
6625
- var CONFIG_SESSION_RE = /^[a-zA-Z0-9_]{1,128}$/;
6626
- function getConfigSessionId(c) {
6627
- return normalizeSessionId(c.req.header("X-Session-Id") || c.req.header("x-session-id"));
6628
- }
6629
- function validateConfigSessionId(sessionId) {
6630
- if (!sessionId) return "缺少 X-Session-Id,无法访问配置中心";
6631
- if (!CONFIG_SESSION_RE.test(sessionId)) {
6632
- return "X-Session-Id 格式不合法";
6633
- }
6634
- return null;
6635
- }
6636
- function getConfigsTableName(sessionId) {
6637
- return "".concat(sessionId.replace('-', '_'), "__config__");
6638
- }
6639
- function normalizeValues(values) {
6640
- if (!values || _typeof$1(values) !== "object" || Array.isArray(values)) {
6641
- return {};
6642
- }
6643
- return values;
6644
- }
6645
- function buildFieldStatus(values) {
6646
- return Object.fromEntries(Object.entries(values).map(function (_ref) {
6647
- var _ref2 = _slicedToArray(_ref, 2),
6648
- key = _ref2[0],
6649
- value = _ref2[1];
6650
- return [key, {
6651
- configured: value !== null && value !== undefined && String(value).trim() !== ""
6652
- }];
6653
- }));
6654
- }
6655
- function validateNamespace(namespace) {
6656
- if (!namespace) return "缺少 namespace";
6657
- if (!CONFIG_NAMESPACE_RE.test(namespace)) {
6658
- return "namespace 只能包含字母、数字、下划线和连字符,且必须以字母开头";
6659
- }
6660
- return null;
6661
- }
6662
- function toConfigResponse(row, fallbackNamespace) {
6663
- var values = normalizeValues(row === null || row === void 0 ? void 0 : row.values);
6664
- return {
6665
- id: row === null || row === void 0 ? void 0 : row.id,
6666
- namespace: (row === null || row === void 0 ? void 0 : row.namespace) || fallbackNamespace,
6667
- values: values,
6668
- fields: buildFieldStatus(values),
6669
- created_at: row === null || row === void 0 ? void 0 : row.created_at,
6670
- updated_at: row === null || row === void 0 ? void 0 : row.updated_at
6671
- };
6672
- }
6673
- function getConfig(_x) {
6674
- return _getConfig.apply(this, arguments);
6675
- }
6676
- function _getConfig() {
6677
- _getConfig = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(c) {
6678
- var namespace, namespaceError, _response, sessionId, sessionError, _response2, tableName, supabase, _yield$supabase$from$, data, error, response, _response3, _t;
6679
- return _regeneratorRuntime.wrap(function (_context) {
6680
- while (1) switch (_context.prev = _context.next) {
6681
- case 0:
6682
- _context.prev = 0;
6683
- namespace = (c.req.query("namespace") || "").trim();
6684
- namespaceError = validateNamespace(namespace);
6685
- if (!namespaceError) {
6686
- _context.next = 1;
6687
- break;
6688
- }
6689
- _response = {
6690
- success: false,
6691
- message: namespaceError
6692
- };
6693
- return _context.abrupt("return", c.json(_response, 200));
6694
- case 1:
6695
- sessionId = getConfigSessionId(c);
6696
- sessionError = validateConfigSessionId(sessionId);
6697
- if (!sessionError) {
6698
- _context.next = 2;
6699
- break;
6700
- }
6701
- _response2 = {
6702
- success: false,
6703
- message: sessionError
6704
- };
6705
- return _context.abrupt("return", c.json(_response2, 200));
6706
- case 2:
6707
- tableName = getConfigsTableName(sessionId); // await ensureConfigsTable(tableName)
6708
- supabase = getSupabase();
6709
- _context.next = 3;
6710
- return supabase.from(tableName).select("*").eq("namespace", namespace).maybeSingle();
6711
- case 3:
6712
- _yield$supabase$from$ = _context.sent;
6713
- data = _yield$supabase$from$.data;
6714
- error = _yield$supabase$from$.error;
6715
- if (!error) {
6716
- _context.next = 4;
6717
- break;
6718
- }
6719
- throw error;
6720
- case 4:
6721
- response = {
6722
- success: true,
6723
- data: toConfigResponse(data, namespace)
6724
- };
6725
- return _context.abrupt("return", c.json(response, 200));
6726
- case 5:
6727
- _context.prev = 5;
6728
- _t = _context["catch"](0);
6729
- console.error("获取配置失败:", _t);
6730
- _response3 = {
6731
- success: false,
6732
- message: "获取配置失败",
6733
- error: _t.message
6734
- };
6735
- return _context.abrupt("return", c.json(_response3, 500));
6736
- case 6:
6737
- case "end":
6738
- return _context.stop();
6739
- }
6740
- }, _callee, null, [[0, 5]]);
6741
- }));
6742
- return _getConfig.apply(this, arguments);
6743
- }
6744
- function updateConfig(_x2) {
6745
- return _updateConfig.apply(this, arguments);
6746
- }
6747
- function _updateConfig() {
6748
- _updateConfig = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(c) {
6749
- var namespace, namespaceError, _response4, body, values, sessionId, sessionError, _response5, tableName, supabase, _yield$supabase$from$2, existing, existingError, nextValues, _yield$supabase$from$3, data, error, response, _response6, _t2;
6750
- return _regeneratorRuntime.wrap(function (_context2) {
6751
- while (1) switch (_context2.prev = _context2.next) {
6752
- case 0:
6753
- _context2.prev = 0;
6754
- namespace = (c.req.param("namespace") || "").trim();
6755
- namespaceError = validateNamespace(namespace);
6756
- if (!namespaceError) {
6757
- _context2.next = 1;
6758
- break;
6759
- }
6760
- _response4 = {
6761
- success: false,
6762
- message: namespaceError
6763
- };
6764
- return _context2.abrupt("return", c.json(_response4, 200));
6765
- case 1:
6766
- _context2.next = 2;
6767
- return c.req.json();
6768
- case 2:
6769
- body = _context2.sent;
6770
- values = normalizeValues(body === null || body === void 0 ? void 0 : body.values);
6771
- sessionId = getConfigSessionId(c);
6772
- sessionError = validateConfigSessionId(sessionId);
6773
- if (!sessionError) {
6774
- _context2.next = 3;
6775
- break;
6776
- }
6777
- _response5 = {
6778
- success: false,
6779
- message: sessionError
6780
- };
6781
- return _context2.abrupt("return", c.json(_response5, 200));
6782
- case 3:
6783
- tableName = getConfigsTableName(sessionId); // await ensureConfigsTable(tableName)
6784
- supabase = getSupabase();
6785
- _context2.next = 4;
6786
- return supabase.from(tableName).select("values").eq("namespace", namespace).maybeSingle();
6787
- case 4:
6788
- _yield$supabase$from$2 = _context2.sent;
6789
- existing = _yield$supabase$from$2.data;
6790
- existingError = _yield$supabase$from$2.error;
6791
- if (!existingError) {
6792
- _context2.next = 5;
6793
- break;
6794
- }
6795
- throw existingError;
6796
- case 5:
6797
- nextValues = _objectSpread(_objectSpread({}, normalizeValues(existing === null || existing === void 0 ? void 0 : existing.values)), values);
6798
- _context2.next = 6;
6799
- return supabase.from(tableName).upsert({
6800
- namespace: namespace,
6801
- values: nextValues,
6802
- updated_at: new Date().toISOString()
6803
- }, {
6804
- onConflict: "namespace"
6805
- }).select("*").single();
6806
- case 6:
6807
- _yield$supabase$from$3 = _context2.sent;
6808
- data = _yield$supabase$from$3.data;
6809
- error = _yield$supabase$from$3.error;
6810
- if (!error) {
6811
- _context2.next = 7;
6812
- break;
6813
- }
6814
- throw error;
6815
- case 7:
6816
- response = {
6817
- success: true,
6818
- message: "配置保存成功",
6819
- data: toConfigResponse(data, namespace)
6820
- };
6821
- return _context2.abrupt("return", c.json(response, 200));
6822
- case 8:
6823
- _context2.prev = 8;
6824
- _t2 = _context2["catch"](0);
6825
- console.error("保存配置失败:", _t2);
6826
- _response6 = {
6827
- success: false,
6828
- message: "保存配置失败",
6829
- error: _t2.message
6830
- };
6831
- return _context2.abrupt("return", c.json(_response6, 500));
6832
- case 9:
6833
- case "end":
6834
- return _context2.stop();
6835
- }
6836
- }, _callee2, null, [[0, 8]]);
6837
- }));
6838
- return _updateConfig.apply(this, arguments);
6839
- }
6840
-
6841
6933
  var AUTH_REQUIRED = "CMS_AUTH_REQUIRED";
6842
6934
  var AUTH_INVALID = "CMS_AUTH_INVALID";
6843
6935
  var CMS_FORBIDDEN = "CMS_FORBIDDEN";
@@ -7277,10 +7369,26 @@ function createDynamicAuthRoute(app) {
7277
7369
  var tableName = c.req.param("tableName");
7278
7370
  return signup(c, tableName);
7279
7371
  });
7372
+ app.post("/auth/password/forgot/:tableName", function (c) {
7373
+ var tableName = c.req.param("tableName");
7374
+ return forgotPassword(c, tableName);
7375
+ });
7376
+ app.post("/auth/password/reset/:tableName", function (c) {
7377
+ var tableName = c.req.param("tableName");
7378
+ return resetPassword(c, tableName);
7379
+ });
7280
7380
  app.post("/auth/:tableName/login", function (c) {
7281
7381
  var tableName = c.req.param("tableName");
7282
7382
  return login(c, tableName);
7283
7383
  });
7384
+ app.post("/auth/:tableName/password/forgot", function (c) {
7385
+ var tableName = c.req.param("tableName");
7386
+ return forgotPassword(c, tableName);
7387
+ });
7388
+ app.post("/auth/:tableName/password/reset", function (c) {
7389
+ var tableName = c.req.param("tableName");
7390
+ return resetPassword(c, tableName);
7391
+ });
7284
7392
  app.get("/auth/:tableName/current", function (c) {
7285
7393
  var tableName = c.req.param("tableName");
7286
7394
  return getCurrentUser(c, tableName);
@@ -7333,17 +7441,9 @@ function createOssUploadRoute(app) {
7333
7441
  app.post("/upload", requireJwtAuth, requireAdminRole, uploadToOss);
7334
7442
  return app;
7335
7443
  }
7336
- function createConfigRoute(app) {
7337
- app.get("/configs", requireAdminRole, getConfig);
7338
- app.put("/configs/:namespace", requireAdminRole, function (c) {
7339
- return updateConfig(c);
7340
- });
7341
- return app;
7342
- }
7343
7444
  // 一键创建所有CMS路由
7344
7445
  function createCmsRoutes(app) {
7345
7446
  createModelRoute(app);
7346
- createConfigRoute(app);
7347
7447
  createDynamicDataRoute(app);
7348
7448
  createDynamicAuthRoute(app);
7349
7449
  return app;
@@ -7359,7 +7459,6 @@ exports.closeDatabase = closeSupabase;
7359
7459
  exports.closeSupabase = closeSupabase;
7360
7460
  exports.createAuthRoute = createAuthRoute;
7361
7461
  exports.createCmsRoutes = createCmsRoutes;
7362
- exports.createConfigRoute = createConfigRoute;
7363
7462
  exports.createDataRoute = createDataRoute;
7364
7463
  exports.createDynamicAuthRoute = createDynamicAuthRoute;
7365
7464
  exports.createDynamicDataRoute = createDynamicDataRoute;
@@ -7371,9 +7470,9 @@ exports.deleteModel = deleteModel;
7371
7470
  exports.deleteTableData = deleteTableData;
7372
7471
  exports.dropForeignKeys = dropForeignKeys;
7373
7472
  exports.executeSupabaseSetup = executeSupabaseSetup;
7473
+ exports.feishuAlertConfig = feishuAlertConfig;
7374
7474
  exports.getAuthService = getAuthService;
7375
7475
  exports.getCmsModelService = getCmsModelService;
7376
- exports.getConfig = getConfig;
7377
7476
  exports.getCurrentUser = getCurrentUser;
7378
7477
  exports.getDatabase = getSupabase;
7379
7478
  exports.getDynamicTableService = getDynamicTableService;
@@ -7390,12 +7489,13 @@ exports.initializeDatabase = initializeSupabase;
7390
7489
  exports.initializeOssUpload = initializeOssUpload;
7391
7490
  exports.initializeSupabase = initializeSupabase;
7392
7491
  exports.login = login;
7492
+ exports.notifyCmsCrudErrorToFeishu = notifyCmsCrudErrorToFeishu;
7493
+ exports.reportCmsCrudErrorToFeishu = reportCmsCrudErrorToFeishu;
7393
7494
  exports.requireAuth = requireAuth;
7394
7495
  exports.signup = signup;
7395
7496
  exports.signupStatus = signupStatus;
7396
7497
  exports.syncDatabase = initializeCmsSystem;
7397
7498
  exports.testConnection = testConnection;
7398
- exports.updateConfig = updateConfig;
7399
7499
  exports.updateModel = updateModel;
7400
7500
  exports.updateTableData = updateTableData;
7401
7501
  exports.uploadToOss = uploadToOss;