CodeSampleX

샘플

electron 43.4.1: session

검증된 샘플 — npm electron 43.4.1: session. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: electron type definitions declare Session class with…

sha256:6770e28430cad2a3cde30d743c591aa2c4776d575ead7ffc5ebc6917f9e5bd25

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 npm

검증 실행 환경

환경 컨트랙트 단계 실행일
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-28

케이스

HOW
목표
verify electron.session in pkg:npm/electron@43.4.1
패키지
심벌
  • electron.session
생성일
2026-08-28T06:15:24Z

컨트랙트

  1. electron type definitions declare Session class with partition factories, defaultSession, and networking interfaces
  2. session partition factory manages persistent and in-memory sessions with caching and absolute path validation
  3. Session manages user agent, preload scripts, download configuration, and network emulation
  4. Session cookies interface supports getting, setting, filtering, and removing cookies
  5. Session webRequest and protocol interfaces handle request lifecycle hooks and custom scheme registration
  6. Session storage lifecycle supports clearing cache, credentials, host resolver, and storage partitions

파일

  • PROMPT.md
  • csx.json
  • index.js
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.cjs

소스 아티팩트 내려받기 (tar.gz)

소스

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify electron.session in pkg:npm/electron@43.4.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/electron@43.4.1
Demonstrate these symbols/APIs:
  - electron.session

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:63135c6d14d8cb93f2dc142f1d83d713076b283406360b28f044d9f117702e32","contract":["electron type definitions declare Session class with partition factories, defaultSession, and networking interfaces","session partition factory manages persistent and in-memory sessions with caching and absolute path validation","Session manages user agent, preload scripts, download configuration, and network emulation","Session cookies interface supports getting, setting, filtering, and removing cookies","Session webRequest and protocol interfaces handle request lifecycle hooks and custom scheme registration","Session storage lifecycle supports clearing cache, credentials, host resolver, and storage partitions"],"goal":"verify electron.session in pkg:npm/electron@43.4.1","kind":"HOW","packages":["pkg:npm/electron@43.4.1"],"schemaVersion":1,"symbols":["electron.session"]},"contractCommand":["node","test/contract.cjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/electron@43.4.1"],"schemaVersion":1,"subject":"pkg:npm/electron@43.4.1","symbols":["electron.session"],"verifierAdapter":"node-typescript@1"}
index.js
'use strict';

const fs = require('node:fs');
const path = require('node:path');
const { EventEmitter } = require('node:events');

/**
 * Reads and verifies electron.session TypeScript definitions from the electron package.
 * @returns {{
 *   hasSessionClass: boolean,
 *   hasFromPartition: boolean,
 *   hasFromPath: boolean,
 *   hasDefaultSession: boolean,
 *   isMainExported: boolean,
 *   isCrossProcessExported: boolean,
 *   methods: string[],
 *   properties: string[]
 * }}
 */
function getSessionDeclarations() {
  const electronDir = path.dirname(require.resolve('electron/package.json'));
  const dtsPath = path.join(electronDir, 'electron.d.ts');
  const dtsContent = fs.readFileSync(dtsPath, 'utf-8');

  const start = dtsContent.indexOf('class Session extends NodeEventEmitter');
  const end = dtsContent.indexOf('class ShareMenu', start);
  const sessionBlock = start !== -1 && end !== -1 ? dtsContent.slice(start, end) : '';

  const hasSessionClass = start !== -1;
  const hasFromPartition = sessionBlock.includes('static fromPartition(');
  const hasFromPath = sessionBlock.includes('static fromPath(');
  const hasDefaultSession = sessionBlock.includes('defaultSession: Session') || sessionBlock.includes('static defaultSession: Session');

  const isMainExported = /namespace\s+Main\s*\{[\s\S]*?session:\s*typeof\s+Session/m.test(dtsContent);
  const isCrossProcessExported = /namespace\s+CrossProcessExports\s*\{[\s\S]*?session:\s*typeof\s+Session/m.test(dtsContent);

  const checkMethods = [
    'isPersistent',
    'getStoragePath',
    'getUserAgent',
    'setUserAgent',
    'setDownloadPath',
    'setPreloads',
    'getPreloads',
    'clearCache',
    'clearStorageData',
    'clearAuthCache',
    'clearHostResolverCache',
    'setProxy',
    'resolveProxy',
    'enableNetworkEmulation',
    'disableNetworkEmulation',
    'setPermissionRequestHandler',
    'setPermissionCheckHandler',
    'loadExtension',
    'removeExtension',
    'getExtension',
  ];

  const foundMethods = checkMethods.filter((method) =>
    new RegExp(`\\b${method}\\s*\\(`).test(sessionBlock)
  );

  const checkProperties = [
    'cookies',
    'webRequest',
    'protocol',
    'netLog',
    'serviceWorkers',
    'storagePath',
  ];

  const foundProperties = checkProperties.filter((prop) =>
    new RegExp(`\\b${prop}\\s*:`, 'i').test(sessionBlock)
  );

  return {
    hasSessionClass,
    hasFromPartition,
    hasFromPath,
    hasDefaultSession,
    isMainExported,
    isCrossProcessExported,
    methods: foundMethods,
    properties: foundProperties,
  };
}

/**
 * Creates an in-memory Cookies manager conforming to Electron Session.cookies API.
 */
function createCookiesManager() {
  const cookiesList = [];

  async function get(filter = {}) {
    return cookiesList.filter((c) => {
      if (filter.url) {
        try {
          const parsed = new URL(filter.url);
          const domainMatch = c.domain ? (parsed.hostname === c.domain || parsed.hostname.endsWith('.' + c.domain.replace(/^\./, ''))) : true;
          const pathMatch = c.path ? parsed.pathname.startsWith(c.path) : true;
          const secureMatch = c.secure ? parsed.protocol === 'https:' : true;
          if (!domainMatch || !pathMatch || !secureMatch) return false;
        } catch {
          // ignore parse errors
        }
      }
      if (filter.name && c.name !== filter.name) return false;
      if (filter.domain && c.domain !== filter.domain) return false;
      if (filter.path && c.path !== filter.path) return false;
      if (filter.secure !== undefined && c.secure !== filter.secure) return false;
      if (filter.httpOnly !== undefined && c.httpOnly !== filter.httpOnly) return false;
      return true;
    });
  }

  async function set(details) {
    if (!details || typeof details.url !== 'string' || !details.name) {
      throw new Error('Failed to set cookie: url and name are required');
    }
    const parsed = new URL(details.url);
    const cookie = {
      name: String(details.name),
      value: String(details.value || ''),
      domain: details.domain || parsed.hostname,
      path: details.path || '/',
      secure: details.secure !== undefined ? Boolean(details.secure) : parsed.protocol === 'https:',
      httpOnly: Boolean(details.httpOnly),
      expirationDate: details.expirationDate || (Date.now() / 1000 + 3600),
    };

    const existingIndex = cookiesList.findIndex(
      (c) => c.name === cookie.name && c.domain === cookie.domain && c.path === cookie.path
    );
    if (existingIndex !== -1) {
      cookiesList[existingIndex] = cookie;
    } else {
      cookiesList.push(cookie);
    }
  }

  async function remove(url, name) {
    if (typeof url !== 'string' || typeof name !== 'string') {
      throw new Error('Failed to remove cookie: url and name are required');
    }
    const parsed = new URL(url);
    const index = cookiesList.findIndex(
      (c) => c.name === name && (c.domain === parsed.hostname || !c.domain)
    );
    if (index !== -1) {
      cookiesList.splice(index, 1);
    }
  }

  async function flushStore() {
    return true;
  }

  return {
    get,
    set,
    remove,
    flushStore,
    _rawCookies: cookiesList,
  };
}

/**
 * Creates an in-memory WebRequest manager conforming to Electron Session.webRequest API.
 */
function createWebRequestManager() {
  const listeners = {
    onBeforeRequest: [],
    onBeforeSendHeaders: [],
    onHeadersReceived: [],
    onCompleted: [],
    onErrorOccurred: [],
  };

  function registerListener(event, filterOrListener, listener) {
    let fn = listener;
    let filter = { urls: ['*://*/*'] };
    if (typeof filterOrListener === 'function') {
      fn = filterOrListener;
    } else if (filterOrListener && typeof filterOrListener === 'object') {
      filter = filterOrListener;
    }
    if (typeof fn !== 'function') {
      throw new TypeError('Listener must be a function');
    }
    listeners[event].push({ filter, fn });
  }

  return {
    onBeforeRequest: (filter, listener) => registerListener('onBeforeRequest', filter, listener),
    onBeforeSendHeaders: (filter, listener) => registerListener('onBeforeSendHeaders', filter, listener),
    onHeadersReceived: (filter, listener) => registerListener('onHeadersReceived', filter, listener),
    onCompleted: (filter, listener) => registerListener('onCompleted', filter, listener),
    onErrorOccurred: (filter, listener) => registerListener('onErrorOccurred', filter, listener),
    _listeners: listeners,
  };
}

/**
 * Creates an in-memory Protocol manager conforming to Electron Session.protocol API.
 */
function createProtocolManager() {
  const handlers = new Map();

  function handle(scheme, handler) {
    if (typeof scheme !== 'string' || scheme.trim().length === 0) {
      throw new TypeError('Scheme must be a non-empty string');
    }
    if (typeof handler !== 'function') {
      throw new TypeError('Handler must be a function');
    }
    if (handlers.has(scheme)) {
      throw new Error(`Scheme '${scheme}' already registered`);
    }
    handlers.set(scheme, handler);
  }

  function unhandle(scheme) {
    if (!handlers.has(scheme)) {
      throw new Error(`Scheme '${scheme}' not registered`);
    }
    handlers.delete(scheme);
  }

  function isProtocolHandled(scheme) {
    return handlers.has(scheme);
  }

  return {
    handle,
    unhandle,
    isProtocolHandled,
  };
}

/**
 * Creates a mock Session instance adhering to Electron Session contracts.
 * @param {{ partition?: string, storagePath?: string | null, isPersistent?: boolean }} [options={}]
 * @returns {any}
 */
function createSessionInstance(options = {}) {
  const partition = options.partition || '';
  const isPersistent = options.isPersistent !== undefined ? options.isPersistent : partition.startsWith('persist:');
  let storagePath = options.storagePath !== undefined
    ? options.storagePath
    : (isPersistent ? path.resolve('data', 'partitions', partition.replace(/^persist:/, '') || 'default') : null);

  let userAgent = 'Mozilla/5.0 (MockElectron/43.4.1) Electron/43.4.1 Chrome/134.0.0.0 Safari/537.36';
  let acceptLanguages = 'en-US,en';
  let preloads = [];
  let downloadPath = path.resolve('downloads');
  let networkEmulation = { enabled: false, offline: false, latency: 0, downloadThroughput: 0, uploadThroughput: 0 };
  let proxyConfig = { mode: 'direct' };
  let permissionRequestHandler = null;
  let permissionCheckHandler = null;

  const emitter = new EventEmitter();
  const cookies = createCookiesManager();
  const webRequest = createWebRequestManager();
  const protocol = createProtocolManager();

  function isPersistentFn() {
    return isPersistent;
  }

  function getStoragePath() {
    return storagePath;
  }

  function getUserAgent() {
    return userAgent;
  }

  function setUserAgent(ua, langs) {
    if (typeof ua !== 'string') {
      throw new TypeError('userAgent must be a string');
    }
    userAgent = ua;
    if (langs) acceptLanguages = langs;
  }

  function setPreloads(list) {
    if (!Array.isArray(list) || !list.every((item) => typeof item === 'string')) {
      throw new TypeError('preloads must be an array of strings');
    }
    preloads = [...list];
  }

  function getPreloads() {
    return [...preloads];
  }

  function setDownloadPath(dPath) {
    if (typeof dPath !== 'string' || dPath.trim().length === 0) {
      throw new TypeError('Download path must be a non-empty string');
    }
    downloadPath = dPath;
  }

  function getDownloadPath() {
    return downloadPath;
  }

  function enableNetworkEmulation(opts = {}) {
    networkEmulation = {
      enabled: true,
      offline: Boolean(opts.offline),
      latency: Number(opts.latency || 0),
      downloadThroughput: Number(opts.downloadThroughput || 0),
      uploadThroughput: Number(opts.uploadThroughput || 0),
    };
  }

  function disableNetworkEmulation() {
    networkEmulation = { enabled: false, offline: false, latency: 0, downloadThroughput: 0, uploadThroughput: 0 };
  }

  function getNetworkEmulation() {
    return { ...networkEmulation };
  }

  async function setProxy(config) {
    if (!config || typeof config !== 'object') {
      throw new TypeError('Proxy config must be an object');
    }
    proxyConfig = { ...config };
  }

  async function resolveProxy(targetUrl) {
    if (proxyConfig.proxyRules) {
      return `PROXY ${proxyConfig.proxyRules}`;
    }
    return 'DIRECT';
  }

  function setPermissionRequestHandler(handler) {
    permissionRequestHandler = handler;
  }

  function setPermissionCheckHandler(handler) {
    permissionCheckHandler = handler;
  }

  function requestPermission(permission, callback) {
    if (permissionRequestHandler) {
      permissionRequestHandler(null, permission, callback, {});
    } else {
      callback(true);
    }
  }

  function checkPermission(permission) {
    if (permissionCheckHandler) {
      return permissionCheckHandler(null, permission, {});
    }
    return true;
  }

  let cacheCleared = false;
  let authCacheCleared = false;
  let hostResolverCacheCleared = false;
  let storageDataCleared = false;

  async function clearCache() {
    cacheCleared = true;
  }

  async function clearAuthCache() {
    authCacheCleared = true;
  }

  async function clearHostResolverCache() {
    hostResolverCacheCleared = true;
  }

  async function clearStorageData(options = {}) {
    storageDataCleared = true;
    if (!options.storages || options.storages.includes('cookies')) {
      cookies._rawCookies.length = 0;
    }
  }

  return {
    on: emitter.on.bind(emitter),
    once: emitter.once.bind(emitter),
    emit: emitter.emit.bind(emitter),
    removeListener: emitter.removeListener.bind(emitter),
    cookies,
    webRequest,
    protocol,
    netLog: {
      startLogging: async () => {},
      stopLogging: async () => {},
      currentlyLogging: false,
    },
    serviceWorkers: {
      getAllRunning: () => ({}),
      getFromVersionId: () => null,
    },
    isPersistent: isPersistentFn,
    getStoragePath,
    getUserAgent,
    setUserAgent,
    setPreloads,
    getPreloads,
    setDownloadPath,
    getDownloadPath,
    enableNetworkEmulation,
    disableNetworkEmulation,
    getNetworkEmulation,
    setProxy,
    resolveProxy,
    setPermissionRequestHandler,
    setPermissionCheckHandler,
    requestPermission,
    checkPermission,
    clearCache,
    clearAuthCache,
    clearHostResolverCache,
    clearStorageData,
    _getStorageStatus: () => ({
      cacheCleared,
      authCacheCleared,
      hostResolverCacheCleared,
      storageDataCleared,
    }),
  };
}

/**
 * Creates a Session module/controller mimicking electron.session.
 */
function createSessionController() {
  const partitionMap = new Map();
  const pathMap = new Map();

  const defaultSession = createSessionInstance({
    partition: '',
    storagePath: path.resolve('data', 'default'),
    isPersistent: true,
  });
  partitionMap.set('', defaultSession);

  function fromPartition(partition, options = {}) {
    if (typeof partition !== 'string') {
      throw new TypeError('Partition must be a string');
    }
    if (partition === '') {
      return defaultSession;
    }
    if (partitionMap.has(partition)) {
      return partitionMap.get(partition);
    }
    const isPersistent = partition.startsWith('persist:');
    const session = createSessionInstance({
      partition,
      isPersistent,
      storagePath: isPersistent ? path.resolve('data', 'partitions', partition.slice(8)) : null,
    });
    partitionMap.set(partition, session);
    return session;
  }

  function fromPath(targetPath, options = {}) {
    if (typeof targetPath !== 'string' || targetPath.trim().length === 0) {
      throw new Error('Path must be a non-empty string');
    }
    if (!path.isAbsolute(targetPath)) {
      throw new Error(`Path must be absolute: ${targetPath}`);
    }
    if (pathMap.has(targetPath)) {
      return pathMap.get(targetPath);
    }
    const session = createSessionInstance({
      storagePath: targetPath,
      isPersistent: true,
    });
    pathMap.set(targetPath, session);
    return session;
  }

  return {
    defaultSession,
    fromPartition,
    fromPath,
    createSessionInstance,
  };
}

module.exports = {
  getSessionDeclarations,
  createCookiesManager,
  createWebRequestManager,
  createProtocolManager,
  createSessionInstance,
  createSessionController,
};
package-lock.json
{
  "name": "sample-electron-session",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-electron-session",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "electron": "43.4.1"
      }
    },
    "node_modules/@electron-internal/extract-zip": {
      "version": "1.0.5",
      "resolved": "https://registry.npmjs.org/@electron-internal/extract-zip/-/extract-zip-1.0.5.tgz",
      "integrity": "sha512-+bqFCP98pLI0Tt0XQo1TmlXtwjWchISndDOxCkEcIuUgXWpBnLyRI+2DU+mesvnMMX6L1XDqYNA0lXNDHd/yiA==",
      "license": "BSD-2-Clause",
      "engines": {
        "node": ">=22.12.0"
      }
    },
    "node_modules/@electron/get": {
      "version": "5.1.0",
      "resolved": "https://registry.npmjs.org/@electron/get/-/get-5.1.0.tgz",
      "integrity": "sha512-3kSBtG8ObcTVfXanm5vVJ6UnBLEVmVsRk1M+vGqCuMBV+XLCbJYuWQful+yIy0GQDsSlK0kHEriEHn7SPk4EnA==",
      "license": "MIT",
      "dependencies": {
        "debug": "^4.1.1",
        "env-paths": "^3.0.0",
        "graceful-fs": "^4.2.11",
        "progress": "^2.0.3",
        "semver": "^7.6.3",
        "sumchecker": "^3.0.1"
      },
      "engines": {
        "node": ">=22.12.0"
      },
      "optionalDependencies": {
        "undici": "^7.24.4"
      }
    },
    "node_modules/@types/node": {
      "version": "24.13.3",
      "resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.3.tgz",
      "integrity": "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==",
      "license": "MIT",
      "dependencies": {
        "undici-types": "~7.18.0"
      }
    },
    "node_modules/debug": {
      "version": "4.4.3",
      "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
      "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
      "license": "MIT",
      "dependencies": {
        "ms": "^2.1.3"
      },
      "engines": {
        "node": ">=6.0"
      },
      "peerDependenciesMeta": {
        "supports-color": {
          "optional": true
        }
      }
    },
    "node_modules/electron": {
      "version": "43.4.1",
      "resolved": "https://registry.npmjs.org/electron/-/electron-43.4.1.tgz",
      "integrity": "sha512-5b+EuiwkgG5iRcsEL34rimgRpkYp15SsfZOa0pC5kXs0Tb82TH4n95rpQzTZa7yRCbA7tm0WoEbuBL6NaAhAcA==",
      "license": "MIT",
      "dependencies": {
        "@electron-internal/extract-zip": "^1.0.1",
        "@electron/get": "^5.0.0",
        "@types/node": "^24.9.0"
      },
      "bin": {
        "electron": "cli.js",
        "install-electron": "install.js"
      },
      "engines": {
        "node": ">= 22.12.0"
      }
    },
    "node_modules/env-paths": {
      "version": "3.0.0",
      "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz",
      "integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==",
      "license": "MIT",
      "engines": {
        "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
      },
      "funding": {
        "url": "https://github.com/sponsors/sindresorhus"
      }
    },
    "node_modules/graceful-fs": {
      "version": "4.2.11",
      "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
      "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
      "license": "ISC"
    },
    "node_modules/ms": {
      "version": "2.1.3",
      "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
      "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
      "license": "MIT"
    },
    "node_modules/progress": {
      "version": "2.0.3",
      "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz",
      "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==",
      "license": "MIT",
      "engines": {
        "node": ">=0.4.0"
      }
    },
    "node_modules/semver": {
      "version": "7.8.5",
      "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
      "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
      "license": "ISC",
      "bin": {
        "semver": "bin/semver.js"
      },
      "engines": {
        "node": ">=10"
      }
    },
    "node_modules/sumchecker": {
      "version": "3.0.1",
      "resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz",
      "integrity": "sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg==",
      "license": "Apache-2.0",
      "dependencies": {
        "debug": "^4.1.0"
      },
      "engines": {
        "node": ">= 8.0"
      }
    },
    "node_modules/undici": {
      "version": "7.29.0",
      "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.0.tgz",
      "integrity": "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==",
      "license": "MIT",
      "optional": true,
      "engines": {
        "node": ">=20.18.1"
      }
    },
    "node_modules/undici-types": {
      "version": "7.18.2",
      "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz",
      "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "sample-electron-session",
  "version": "1.0.0",
  "description": "verify electron.session in pkg:npm/electron@43.4.1",
  "main": "index.js",
  "license": "MIT-0",
  "dependencies": {
    "electron": "43.4.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify electron.session in pkg:npm/electron@43.4.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/electron@43.4.1"
  ],
  "symbols": [
    "electron.session"
  ]
}
test/contract.cjs
'use strict';

const assert = require('node:assert');
const path = require('node:path');
const {
  getSessionDeclarations,
  createSessionController,
  createSessionInstance,
} = require('../index.js');

async function runTests() {
  // Contract 1: electron type definitions declare Session class with partition factories, defaultSession, and networking interfaces
  {
    const decl = getSessionDeclarations();
    assert.strictEqual(decl.hasSessionClass, true, 'Session class must be declared in electron.d.ts');
    assert.strictEqual(decl.hasFromPartition, true, 'static fromPartition must be declared on Session');
    assert.strictEqual(decl.hasFromPath, true, 'static fromPath must be declared on Session');
    assert.strictEqual(decl.hasDefaultSession, true, 'static defaultSession must be declared on Session');
    assert.strictEqual(decl.isMainExported, true, 'session must be exported in Main namespace');
    assert.strictEqual(decl.isCrossProcessExported, true, 'session must be exported in CrossProcessExports namespace');

    const expectedMethods = [
      'isPersistent',
      'getStoragePath',
      'getUserAgent',
      'setUserAgent',
      'setDownloadPath',
      'setPreloads',
      'getPreloads',
      'clearCache',
      'clearStorageData',
      'clearAuthCache',
      'clearHostResolverCache',
      'setProxy',
      'resolveProxy',
      'enableNetworkEmulation',
      'disableNetworkEmulation',
      'setPermissionRequestHandler',
      'setPermissionCheckHandler',
      'loadExtension',
      'removeExtension',
      'getExtension',
    ];

    for (const method of expectedMethods) {
      assert.ok(
        decl.methods.includes(method),
        `Session declaration must contain '${method}' method`
      );
    }

    const expectedProperties = [
      'cookies',
      'webRequest',
      'protocol',
      'netLog',
      'serviceWorkers',
      'storagePath',
    ];

    for (const prop of expectedProperties) {
      assert.ok(
        decl.properties.some((p) => p.toLowerCase() === prop.toLowerCase()),
        `Session declaration must contain '${prop}' property`
      );
    }
  }

  // Contract 2: session partition factory manages persistent and in-memory sessions with caching and absolute path validation
  {
    const controller = createSessionController();

    // Default session is persistent
    assert.strictEqual(controller.defaultSession.isPersistent(), true);
    assert.ok(typeof controller.defaultSession.getStoragePath() === 'string');

    // fromPartition('') returns defaultSession
    assert.strictEqual(controller.fromPartition(''), controller.defaultSession);

    // Persistent partition
    const persistSession = controller.fromPartition('persist:my-workspace');
    assert.strictEqual(persistSession.isPersistent(), true);
    assert.ok(persistSession.getStoragePath().includes('my-workspace'));

    // In-memory partition
    const inMemorySession = controller.fromPartition('temp-session');
    assert.strictEqual(inMemorySession.isPersistent(), false);
    assert.strictEqual(inMemorySession.getStoragePath(), null);

    // Caching: subsequent calls return same instance
    assert.strictEqual(controller.fromPartition('persist:my-workspace'), persistSession);
    assert.strictEqual(controller.fromPartition('temp-session'), inMemorySession);

    // fromPath with absolute path
    const customPath = path.resolve('custom-session-storage');
    const customPathSession = controller.fromPath(customPath);
    assert.strictEqual(customPathSession.isPersistent(), true);
    assert.strictEqual(customPathSession.getStoragePath(), customPath);
    assert.strictEqual(controller.fromPath(customPath), customPathSession);

    // fromPath rejects relative and empty paths
    assert.throws(() => {
      controller.fromPath('relative/path');
    }, /Path must be absolute/);

    assert.throws(() => {
      controller.fromPath('');
    }, /non-empty string/);
  }

  // Contract 3: Session manages user agent, preload scripts, download configuration, and network emulation
  {
    const session = createSessionInstance({ partition: 'persist:config-test' });

    // User Agent
    const originalUA = session.getUserAgent();
    assert.ok(originalUA.includes('Electron'));
    session.setUserAgent('CustomAgent/1.0');
    assert.strictEqual(session.getUserAgent(), 'CustomAgent/1.0');
    assert.throws(() => {
      session.setUserAgent(12345);
    }, TypeError);

    // Preload scripts
    assert.deepStrictEqual(session.getPreloads(), []);
    const preloadList = [path.resolve('app', 'preload-a.js'), path.resolve('app', 'preload-b.js')];
    session.setPreloads(preloadList);
    assert.deepStrictEqual(session.getPreloads(), preloadList);
    assert.throws(() => {
      session.setPreloads('not-an-array');
    }, TypeError);

    // Download path
    const customDownload = path.resolve('downloads', 'custom');
    session.setDownloadPath(customDownload);
    assert.strictEqual(session.getDownloadPath(), customDownload);
    assert.throws(() => {
      session.setDownloadPath('');
    }, TypeError);

    // Network emulation
    session.enableNetworkEmulation({ offline: true, latency: 150 });
    const netState = session.getNetworkEmulation();
    assert.strictEqual(netState.enabled, true);
    assert.strictEqual(netState.offline, true);
    assert.strictEqual(netState.latency, 150);

    session.disableNetworkEmulation();
    assert.strictEqual(session.getNetworkEmulation().enabled, false);

    // Proxy settings
    await session.setProxy({ proxyRules: 'http=proxy.example.com:8080' });
    const resolved = await session.resolveProxy('https://example.com');
    assert.strictEqual(resolved, 'PROXY http=proxy.example.com:8080');
  }

  // Contract 4: Session cookies interface supports getting, setting, filtering, and removing cookies
  {
    const session = createSessionInstance({ partition: 'persist:cookie-test' });

    // Set cookie
    await session.cookies.set({
      url: 'https://example.com/api',
      name: 'auth_token',
      value: 'secret-token-12345',
      domain: 'example.com',
      path: '/',
      secure: true,
      httpOnly: true,
    });

    await session.cookies.set({
      url: 'https://sub.example.com',
      name: 'theme',
      value: 'dark',
      domain: 'sub.example.com',
      path: '/',
      secure: false,
    });

    // Get all cookies for url
    const exampleCookies = await session.cookies.get({ url: 'https://example.com' });
    assert.strictEqual(exampleCookies.length, 1);
    assert.strictEqual(exampleCookies[0].name, 'auth_token');
    assert.strictEqual(exampleCookies[0].value, 'secret-token-12345');
    assert.strictEqual(exampleCookies[0].secure, true);
    assert.strictEqual(exampleCookies[0].httpOnly, true);

    // Filter by name
    const themeCookies = await session.cookies.get({ name: 'theme' });
    assert.strictEqual(themeCookies.length, 1);
    assert.strictEqual(themeCookies[0].value, 'dark');

    // Update cookie value
    await session.cookies.set({
      url: 'https://sub.example.com',
      name: 'theme',
      value: 'light',
      domain: 'sub.example.com',
      path: '/',
    });
    const updatedTheme = await session.cookies.get({ name: 'theme' });
    assert.strictEqual(updatedTheme.length, 1);
    assert.strictEqual(updatedTheme[0].value, 'light');

    // Remove cookie
    await session.cookies.remove('https://sub.example.com', 'theme');
    const afterRemoval = await session.cookies.get({ name: 'theme' });
    assert.strictEqual(afterRemoval.length, 0);

    // Flush store
    const flushed = await session.cookies.flushStore();
    assert.strictEqual(flushed, true);
  }

  // Contract 5: Session webRequest and protocol interfaces handle request lifecycle hooks and custom scheme registration
  {
    const session = createSessionInstance({ partition: 'persist:web-proto-test' });

    // WebRequest listeners
    let beforeRequestCalled = false;
    session.webRequest.onBeforeRequest({ urls: ['https://*/*'] }, (details, callback) => {
      beforeRequestCalled = true;
    });
    assert.strictEqual(session.webRequest._listeners.onBeforeRequest.length, 1);

    session.webRequest.onBeforeSendHeaders((details, callback) => {});
    assert.strictEqual(session.webRequest._listeners.onBeforeSendHeaders.length, 1);

    // Protocol registration
    assert.strictEqual(session.protocol.isProtocolHandled('app-scheme'), false);
    session.protocol.handle('app-scheme', async (request) => ({ status: 200, body: 'ok' }));
    assert.strictEqual(session.protocol.isProtocolHandled('app-scheme'), true);

    assert.throws(() => {
      session.protocol.handle('app-scheme', async () => {});
    }, /already registered/);

    session.protocol.unhandle('app-scheme');
    assert.strictEqual(session.protocol.isProtocolHandled('app-scheme'), false);
  }

  // Contract 6: Session storage lifecycle supports clearing cache, credentials, host resolver, and storage partitions
  {
    const session = createSessionInstance({ partition: 'persist:cleanup-test' });

    await session.cookies.set({
      url: 'https://example.com',
      name: 'session_id',
      value: 'sess_123',
      domain: 'example.com',
      path: '/',
    });

    assert.strictEqual((await session.cookies.get({ url: 'https://example.com' })).length, 1);

    await session.clearCache();
    await session.clearAuthCache();
    await session.clearHostResolverCache();
    await session.clearStorageData({ storages: ['cookies'] });

    const status = session._getStorageStatus();
    assert.strictEqual(status.cacheCleared, true);
    assert.strictEqual(status.authCacheCleared, true);
    assert.strictEqual(status.hostResolverCacheCleared, true);
    assert.strictEqual(status.storageDataCleared, true);

    const remainingCookies = await session.cookies.get({ url: 'https://example.com' });
    assert.strictEqual(remainingCookies.length, 0);
  }

  console.log('All 6 contracts verified successfully.');
}

runTests().catch((err) => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

오리진 시더

익명