过多设置Cookies导致单点登录跳出

引

公司项目最近遇到一个登录问题:在加载带有 3D TileLayers 倾斜摄影模型的页面时,刷新页面会导致应用退出登录。

问题排查思路

1. 是否是某个业务接口导致的退出?

排查过程中发现一个业务接口报错 500,但 500 错误不应导致鉴权状态丢失。

2. 从”刷新后丢失鉴权状态”入手

由于退出登录现象只在页面刷新后出现,因此从 Cookies 方向开始排查。

项目使用 Keycloak 进行认证,在页面刷新时会初始化客户端实例,并使用 Cookies 中的信息进行 OAuth2 协议鉴权。怀疑是 Cookies 中的鉴权信息丢失或过期。

3. 排查 Cookies

发现某个接口返回了 Set-Cookies 响应头,设置了 JSESSIONID cookie。

起初怀疑是重新设置 JSESSIONID 导致原有值被覆盖。但考虑到其 Path 属性,登录时 path=/ 不会被携带,因此排除此可能。

进一步分析发现,这个 Set-Cookie 本身就不合理。因为单点登录应该在全局使用同一个鉴权状态,这个设置可能是由项目的等保需求引入的。

继续排查所有请求,包括静态资源请求,发现大量静态资源响应都带有 Set-Cookie 头,持续向前端写入 cookies!

查询资料后发现,Chrome 等主流浏览器都对 Cookie 有严格限制。这种持续写入 Cookie 的行为显然存在问题。

以下是各浏览器的 Cookie 限制:

浏览器 单个 Cookie 大小限制 每域名 Cookie 数量限制
Google Chrome 4096 bytes 180 个
Mozilla Firefox 4097 bytes 150 个
Apple Safari 4096 bytes 50 个
Microsoft Edge 4096 bytes 50 个

问题原因

最终确认是由于项目等保要求,在 nginx 上配置了全局 Cookie 设置,导致 Cookie 数量达到浏览器上限,覆盖了原有的鉴权 Cookie。

# 由于我接触不到服务器,这里猜一下大概率是这些配置
proxy_cookie_path / "/; Path=/; Secure; HttpOnly";
add_header Set-Cookie 'mycookie=xxxx;Path=/;SameSite=None; Secure';

问题解决

联系服务器管理员注释掉 nginx 中的 set-cookie 相关配置后,问题得到解决。

Vite插件初探-以自动部署为例

背景

之前写过 Vue(Webpack)的自动打包配置,现在由于新项目使用了 Vite+Vue3+TS 的最新技术栈,旧版写法不通用了,这里重新针对 vite 写一下新脚本,并顺便了解一下 vite 脚本的基本写法。

了解 Vite 脚本

1. 插件配置(使用)

在vite.config.js中的 plugins 中,使用数组形式配置。

// vite.config.js
import vitePlugin from "vite-plugin-feature";
import rollupPlugin from "rollup-plugin-feature";

export default defineConfig({
  plugins: [vitePlugin(), rollupPlugin()],
});

注意到,这里的插件一般指函数,并通过函数参数的形式传递必要参数。

2. 钩子

2.1 通用钩子(Rollup)

以下钩子在服务器启动时被调用:
options
buildStart
以下钩子会在每个传入模块请求时被调用:
resolveId
load
transform
以下钩子在服务器关闭时被调用:
buildEnd
closeBundle
请注意moduleParsed钩子在开发中是 不会 被调用的,因为 Vite 为了性能会避免完整的 AST 解析。

3 情景应用

apply字段表示此插件在哪种情况被调用。可选值:serve,build

自动部署插件

1. 环境变量的配置

用来储存 rsync 同步脚本

#.env
VITE_RSYNC='/usr/bin/rsync --archive --verbose --compress --delete -e  "ssh -i ~/.ssh/id_rsa" /Users/bryan/workspace/radar-screen/dist/ [email protected]:/home/njcm/AppService/h5/radar-screen/'

2. 编写插件主体

/*
 * @Author: 王欣磊
 * @Date: 2022-07-20 10:03:40
 * @LastEditors: 王欣磊
 * @LastEditTime: 2022-07-20 11:34:58
 * @Description:
 * @FilePath: /radar-screen/src/plugins/runNode.ts
 */
import { exec } from "child_process";
// 脚本和钩子
export default function runNode({
  node,
  when,
}: {
  node?: string;
  when: "buildStart" | "buildEnd";
}) {
  return {
    name: "run-node",
    apply: "build",
    [when]() {
      try {
        node &&
          exec(node, (e, s) => {
            if (!e) {
              console.log("\n✅ 部署成功" + s);
            } else {
              console.error(e);
            }
          });
      } catch (err) {
        console.error(err);
      }
    },
  };
}

3. 插件使用

// vite.config.ts
import { defineConfig, loadEnv } from 'vite'
// ...
    plugins: [vue(), { ...runNode({ node: env.VITE_RSYNC, when: 'buildEnd' }), apply: 'build' },],
// ...

MMSI-国籍/国旗一览表

前言

背景

最近公司后端出现了使用MMSI匹配船舶国籍数据的错误问题,原因是参考的MMSI对照表不全。因此我在这重新开发整理了一份列表,采用vite+Vue3打造。

名词解释

MID

Maritime identification digits, 表示船舶国籍代码,一般由MMSI前三位构成。

源码

wangxinlei1997/mid-data-set

直链

MMSI对照表

Vue项目Build后自动打包

1. 安装依赖

npm install filemanager-webpack-plugin

2. vue.config.js 配置

const FileManagerPlugin = require('filemanager-webpack-plugin')
...
// isProd 一般为环境判断 如 process.env.NODE_ENV === 'production'
isProd &&
  plugins.push(
    new FileManagerPlugin({
      events: {
        onEnd: {
          // 首先先删除之前的文件
          delete: ['./dist.zip'],
          // 压缩 源->目的地
          archive: [
            {
              source: path.join(__dirname, './dist'),
              destination: path.join(__dirname, './dist.zip')
            }
          ]
        }
      }
    })
  )
...
const vueConfig = {
  ...
  configureWebpack: {
    ...
    plugins,
    ...
  }
  ...
}

3. filemanager-webpack-plugin 简易教程

Github

1. Options

new FileManagerPlugin({
  events: {
    onStart: {}, //打包前
    onEnd: {}, //打包结束后
  },
  runTasksInSeries: false,
  runOnceInWatchMode: false,
});

2. Actions

  • Copy
    • source[string] - 源(文件/目录/glob)
    • destination[string] - 文件/目录
    • options [‘object`] - copy options
      • flat: [Boolean]
      • preserveTimestamps: [Boolean]
      • overwite: [Boolean]
    • globOptions [object] - options to forward to glob options
  • Delete
  • Move
    • source[string] - a file or a directory or a glob
    • destination[string] - a file or a directory.
  • Mkdir
  • Archive
    • source[string] - a file or a directory or a glob
    • destination[string] - a file.
    • format[string] - Optional. Defaults to extension in destination filename.
    • options[object] - Refer https://www.archiverjs.com/archiver

3. 官方示例

// webpack.config.js:

const FileManagerPlugin = require("filemanager-webpack-plugin");

export default {
  // ...rest of the config
  plugins: [
    new FileManagerPlugin({
      events: {
        onEnd: {
          copy: [
            { source: "/path/fromfile.txt", destination: "/path/tofile.txt" },
            { source: "/path/**/*.js", destination: "/path" },
          ],
          move: [
            { source: "/path/from", destination: "/path/to" },
            { source: "/path/fromfile.txt", destination: "/path/tofile.txt" },
          ],
          delete: ["/path/to/file.txt", "/path/to/directory/"],
          mkdir: ["/path/to/directory/", "/another/directory/"],
          archive: [
            { source: "/path/from", destination: "/path/to.zip" },
            { source: "/path/**/*.js", destination: "/path/to.zip" },
            { source: "/path/fromfile.txt", destination: "/path/to.zip" },
            {
              source: "/path/fromfile.txt",
              destination: "/path/to.zip",
              format: "tar",
            },
            {
              source: "/path/fromfile.txt",
              destination: "/path/to.tar.gz",
              format: "tar",
              options: {
                gzip: true,
                gzipOptions: {
                  level: 1,
                },
                globOptions: {
                  // https://github.com/Yqnn/node-readdir-glob#options
                  dot: true,
                },
              },
            },
          ],
        },
      },
    }),
  ],
};

道格拉斯-普克算法(Ramer–Douglas–Peucker)曲线降采样

背景

在最近开发的某系统中,有一需求是在map上显示路径,并在路径上分段打箭头、点和文字信息(时间)。

测试环境(mock数据)理想效果


看起来还不错是吧
然鹅,但由于真实环境点位数据过于密集,导致显示效果十分魔幻,看起来是这样婶的。(害)

然后呢,突然想起来之前大学时侯做acm的一个路径拟合题和这个需求很类似,就在此分享一下吧
(虽然好像这个算法是由后端实现)。

Ramer–Douglas–Peucker算法

1. 简介

Ramer–Douglas–Peucker算法,又称道格拉斯-普克算法算法或迭代端点拟合算法,是一种将由多点组成的曲线(折线)降采样为点数较小的类似曲线(折线)的算法。

2. 算法思想

起始曲线是一组有序的点或线,距离维度 ε(可以理解为拟合度) > 0。
该算法采用递归思想。最初,运算点集合为所有点。首先,拟合出第一个点和最后一个点的直线,计算当前运算集中所有点到这条直线的距离(循环),如果这个距离(d)<ε,那么可以将除了首尾的两个点以外的所有点去除,形成一个简单线段。否则,如果距离(d)>ε,这个点将被保留,并由此点将原有运算集划分为两个子集,并递归运算这个流程。
当递归完成后,可以生成一条新的输出曲线,该曲线由所有且仅由那些被标记为保留的点组成。
说了这些,有轻微阅读障碍的XDM估计已经躺下了(比如我),所以这里放上一张图来帮助理解。

3. 参数控制

ε(阈值),越小,直线越平滑,越大,直线越锐利。

4. 伪代码

function 道格拉斯(运算点集, 阈值) {
  // 找出两点间点的最大距离
  最大距离 = 0;
  距离最大点位置 = 0;
  length = 运算集.length;
  for (let i = 0; i < length - 1; i++) {
    d = 计算点到直线距离(
      运算点集[i],
      拟合直线方程(运算点集[0], 运算点集[length - 1])
    );
    if (d > 最大距离) {
      距离最大点位置 = i;
      最大距离 = d;
    }
  }

  结果输出 = [];

  // 如果最大距离小于阈值,就拟合
  if (最大距离 > 阈值) {
    // 继续计算
    左子集 = 道格拉斯(运算点集合.slice(0, 距离最大点位置), 阈值);
    右子集 = 道格拉斯(运算点集.slice(距离最大点位置, length), 阈值);
    结果输出 = 左子集.concat(右子集);
  } else {
    // 拟合
    结果输出 = [运算点集[0], 运算点集[length - 1]];
  }
  return 结果输出;
}

5.后记

  • 算法复杂度O(n log n)

End

Cesium之Vue环境配置与demo运行(一)

背景

最近公司有新项目(据说是关于数字孪生),需要用到Cesium来展示3d模型。由于我技术栈是Vue,故在此记录环境配置、安装相关的一些要点。

Vue项目创建

本次Demo尝试使用Vue3来搭建。

  1. 通过Vue-CLI ^4.5+ 脚手架来创建V3项目
    # 安装vli(按需)
    yarn global add @vue/cli
    # OR
    npm install -g @vue/cli
    # 创建项目
    vue create hello-world
    创建过程中注意选择V3即可,其他配置按自己喜好。
  2. 项目创建完成后,在项目下安装sass相关依赖。(按需)
    npm install node-sass
    npm install sass-loader
    由于node-sass的版本和nodejs版本依赖关系比较魔幻,故在安装的时候需要注意和本地的node版本匹配。下放依赖匹配表。
    NodeJS Supported node-sass version Node Module
    Node 15 5.0+ 88
    Node 14 4.14+ 83
    Node 13 4.13+, <5.0 79
    Node 12 4.12+ 72
    Node 11 4.10+, <5.0 67
    Node 10 4.9+ 64
    Node 8 4.5.3+, <5.0 57
    Node <8 <5.0 <57
  3. 安装cesium
    npm install cesium
  4. 安装webpack相关依赖
    copy-webpack-plugin
    css-loader”
    html-webpack-plugin
    strip-pragma-loader
    style-loader
    uglifyjs-webpack-plugin
    url-loader
    webpack
    webpack-cli
    webpack-dev-server
  5. 在项目文件夹下新建vue.config.js
    const path = require("path");
    
    
    const webpack = require('webpack');
    const CopyWebpackPlugin = require('copy-webpack-plugin');
    const resolve = function(dir) {
      return path.join(__dirname, dir);
    };
    module.exports = {
      publicPath: process.env.NODE_ENV === "production" ? "./" : "./",
      outputDir: "dist",
      assetsDir: "static",
      lintOnSave: true, // 是否开启eslint保存检测
      productionSourceMap: false, // 是否在构建生产包时生成sourcdeMap
      chainWebpack: config => {
        config.resolve.alias
          .set("@", resolve("src"))
          .set("@v", resolve("src/views"))
          .set("@c", resolve("src/components"))
          .set("@u", resolve("src/utils"))
          .set("@s", resolve("src/service")); /* 别名配置 */
        config.optimization.runtimeChunk("single");
      },
      devServer: {
        // host: "localhost",
        /* 本地ip地址 */
        //host: "192.168.1.107",
        host: "0.0.0.0", //局域网和本地访问
        port: "8080",
        hot: true,
        /* 自动打开浏览器 */
        open: false,
        overlay: {
          warning: false,
          error: true
        },
        /* 跨域代理 */
      },
      configureWebpack:{
          plugins: [
        // Copy Cesium Assets, Widgets, and Workers to a static directory
        new CopyWebpackPlugin({
            patterns: [
                { from: 'node_modules/cesium/Build/Cesium/Workers', to: 'Workers' },
                { from: 'node_modules/cesium/Build/Cesium/ThirdParty', to: 'ThirdParty' },
                { from: 'node_modules/cesium/Build/Cesium/Assets', to: 'Assets' },
                { from: 'node_modules/cesium/Build/Cesium/Widgets', to: 'Widgets' }
            ],
        }),
        new webpack.DefinePlugin({
            // Define relative base path in cesium for loading assets
            CESIUM_BASE_URL: JSON.stringify('')
        })
    ]
      }
      ,
    };
  6. 在你的HelloWorld里面写cesium相关逻辑

    这里我直接贴上我的HelloWorld
    PS: 其中token自己在Cesium官网里面申请就行了

    <!--
     * @Author: 王欣磊
     * @Date: 2021-05-06 11:17:20
     * @LastEditors: 王欣磊
     * @LastEditTime: 2021-05-06 15:57:10
     * @Description: 
     * @FilePath: /test3/src/components/HelloWorld.vue
    -->
    <template>
      <div class="hello">
        <div id="cesiumContainer"></div>
        <h1 @click="clickChoose">{{ message }} {{item.title}}</h1>
        <p>
          For a guide and recipes on how to configure / customize this project,<br>
          check out the
          <a href="https://cli.vuejs.org" target="_blank" rel="noopener">vue-cli documentation</a>.
        </p>
        <h3>Installed CLI Plugins</h3>
        <ul>
          <li><a href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel" target="_blank" rel="noopener">babel</a></li>
          <li><a href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-eslint" target="_blank" rel="noopener">eslint</a></li>
        </ul>
        <h3>Essential Links</h3>
        <ul>
          <li><a href="https://vuejs.org" target="_blank" rel="noopener">Core Docs</a></li>
          <li><a href="https://forum.vuejs.org" target="_blank" rel="noopener">Forum</a></li>
          <li><a href="https://chat.vuejs.org" target="_blank" rel="noopener">Community Chat</a></li>
          <li><a href="https://twitter.com/vuejs" target="_blank" rel="noopener">Twitter</a></li>
          <li><a href="https://news.vuejs.org" target="_blank" rel="noopener">News</a></li>
        </ul>
        <h3>Ecosystem</h3>
        <ul>
          <li><a href="https://router.vuejs.org" target="_blank" rel="noopener">vue-router</a></li>
          <li><a href="https://vuex.vuejs.org" target="_blank" rel="noopener">vuex</a></li>
          <li><a href="https://github.com/vuejs/vue-devtools#vue-devtools" target="_blank" rel="noopener">vue-devtools</a></li>
          <li><a href="https://vue-loader.vuejs.org" target="_blank" rel="noopener">vue-loader</a></li>
          <li><a href="https://github.com/vuejs/awesome-vue" target="_blank" rel="noopener">awesome-vue</a></li>
        </ul>
      </div>
    </template>
    
    <script>
    import * as Cesium from 'cesium';
    import "cesium/Build/Cesium/Widgets/widgets.css";
    import { onMounted, ref,reactive } from 'vue'
    export default {
      name: 'HelloWorld',
      props: {
        msg: String
      },
      setup(){
        const message = ref('choose')
        const item = reactive({title:'name'})
        onMounted(()=>{
            // Your access token can be found at: https://cesium.com/ion/tokens.
        Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJlYWY5NzY4Yy1mY2YyLTRmYTgtYjAyMy1hMGY3MTllZmVmNDUiLCJpZCI6NTQ4ODMsImlhdCI6MTYyMDI3MzA1NX0.M-B79nr0L9j3L3RmNwmGisLrQz5ux7vRKv7TbP4qxkU';
        // Initialize the Cesium Viewer in the HTML element with the `cesiumContainer` ID.
        const viewer = new Cesium.Viewer('cesiumContainer', {
          terrainProvider: Cesium.createWorldTerrain()
        });    
        // Add Cesium OSM Buildings, a global 3D buildings layer.
        // eslint-disable-next-line no-unused-vars
        const buildingTileset = viewer.scene.primitives.add(Cesium.createOsmBuildings());   
        // Fly the camera to San Francisco at the given longitude, latitude, and height.
        viewer.camera.flyTo({
          destination : Cesium.Cartesian3.fromDegrees(-122.4175, 37.655, 400),
          orientation : {
            heading : Cesium.Math.toRadians(0.0),
            pitch : Cesium.Math.toRadians(-15.0),
          }
        });
        })
        return { message,item}
      },
      methods:{
        clickChoose(){
          this.message+='0'
          this.item.title+='p'
        }
      }
    }
    </script>
    
    <!-- Add "scoped" attribute to limit CSS to this component only -->
    <style scoped lang="scss">
    h3 {
      margin: 40px 0 0;
    }
    ul {
      list-style-type: none;
      padding: 0;
    }
    li {
      display: inline-block;
      margin: 0 10px;
    }
    a {
      color: #42b983;
    }
    </style>
    
  7. 运行devServer就完事了

热区扩大-Vue组件

废话不多说直接上代码

<template>
  <view class="parent">
    <slot></slot>
    <view :class="['expand',area]" @click.stop="emit"></view>
  </view>
</template>

<script>
  export default {
    name: "ExpandClickArea",
    props: {
      area: {
        //small,normal,big,large
        default: "normal",
        type: String,
      },
    },
    methods: {
      emit() {
        this.$emit("expandOnClick");
      },
    },
  };
</script>

<style scoped>
  .parent {
    position: relative;
    overflow-x: visible;
    overflow: visible;
  }
  .expand {
    position: absolute;
  }
  .normal {
    top: -10px;
    right: -10px;
    bottom: -10px;
    left: -10px;
  }
  .small {
    top: -5px;
    right: -5px;
    bottom: -5px;
    left: -5px;
  }
  .big {
    top: -15px;
    right: -15px;
    bottom: -15px;
    left: -15px;
  }
  .large {
    top: -20px;
    right: -20px;
    bottom: -20px;
    left: -20px;
  }
</style>

CSS奇淫技巧

前言

在日常实现一些功能的时候,一些复杂的界面/交互需求往往能使用几行 CSS 来实现,再次做相关记录,以便之后检索。

css 半圆画法(圆边框)

/*右半圆*/
width: 9px;
height: 18px;
border-radius: 0 18px 18px 0;
/*background: #any;*/
border: 1px solid #ff4b33;
border-left: none;

flex 布局下 space-between / space-around 最后一行左对齐

/* 最后一项margin-right:auto */
.item:last-child {
  margin-right: auto;
}

使用 mask 或 clip-path 的时候同时显示阴影

box-shadow 无效

  1. 在父元素上使用 filter 滤镜:drop-shadow

  2. clip 或 mask 在源组件上,而不是在父组件上

  3. drop-shadow 和 box-shadow 的区别:

    • box-shadow 为盒子模型下的阴影渲染
    • drop-shadow 会在非透明像素下投下阴影
<span class="tag-wrap">
  <span class="tag"> Tag </span>
</span>
.tag-wrap {
  filter: drop-shadow(-1px 6px 3px rgba(50, 50, 0, 0.5));
}
.tag {
  background: #fb8c00;
  color: #222;
  padding: 2rem 3rem 2rem 4rem;
  font: bold 32px system-ui;
  clip-path: polygon(30px 0%, 100% 0%, 100% 100%, 30px 100%, 0 50%);
}

图片宽高比自适应

父元素使用 padding 来撑开布局,子元素 absolute 定位宽高 100%

  • 原理:padding 大小是相对于父元素的 width

JS奇淫技巧

前言

本文中记录了 js 的一些技巧/新特性

选择/反选对象中的元素

function pick(obj, keys) {
  return keys
    .map((k) => (k in obj ? { [k]: obj[k] } : {}))
    .reduce((res, o) => Object.assign(res, o), {});
}

const row = {
  "accounts.id": 1,
  "client.name": "John Doe",
  "bank.code": "MDAKW213",
};

const table = [
  row,
  { "accounts.id": 3, "client.name": "Steve Doe", "bank.code": "STV12JB" },
];

pick(row, ["client.name"]); // 取到了 client name

table.map((row) => pick(row, ["client.name"])); // 取到了一系列 client name

function reject(obj, keys) {
  return Object.keys(obj)
    .filter((k) => !keys.includes(k))
    .map((k) => ({ [k]: obj[k] }))
    .reduce((res, o) => Object.assign(res, o), {});
}

// 或者, 利用 pick
function reject(obj, keys) {
  const vkeys = Object.keys(obj).filter((k) => !keys.includes(k));
  return pick(obj, vkeys);
}

reject({ a: 2, b: 3, c: 4 }, ["a", "b"]); // => {c: 4}

只执行一次的函数(闭包法)

function once(fn) {
  let called = false;
  return function () {
    if (!called) {
      called = true;
      fn.apply(this, arguments);
    }
  };
}

相同参数的函数缓存结果

function cached(fn) {
  const cache = Object.create(null);
  return function cachedFn(str) {
    if (!cache[str]) {
      let result = fn(str);
      cache[str] = result;
    }
    return cache[str];
  };
}

compose嵌套式函数链式调用优化

  • 依次执行函数的时候,往往使用以下基本写法

    const res = fun3(fun2(fun1('arg')))

    这种写法一般能满足基本需要。但是如果在嵌套层数更多的情况下,代码就会变得很复杂、难以维护。

  • 在Redux内部compose的写法如下

    function compose(...funs) {
        return funcs.reduce((a, b) => (...args) => a(b(...args)));
    }
    const newfunc = compose(fun3,fun2,fun1)
    const res = newfunc('arg')

    在此函数中,重点为reduce 方法。在使用此方法时,将会依次选用第1个、第2个;第2个、第3个fun,并用后一个函数的执行结果作为前一个的参数,从而实现需要的依次执行效果。

    在本例中,执行的顺序如下:

    1. fun3(fun2(...args)) -> fun3(fun2(fun1(...args)))