From 9a9297c5ef0d9b69cc28bc5e4fe580fe71fed894 Mon Sep 17 00:00:00 2001 From: Aaron de Mello Date: Wed, 4 Nov 2026 15:11:30 -0500 Subject: [PATCH 1/6] test: exercise packed SDK against real HTTP servers --- .github/workflows/pull-reqeust.yml | 3 + jest.config.js | 1 + package.json | 3 +- scripts/testE2E.js | 76 +++++++ tests/e2e/README.md | 15 ++ tests/e2e/package.test.cjs | 174 +++++++++++++++ tests/e2e/resources.test.cjs | 346 +++++++++++++++++++++++++++++ tests/e2e/transport.test.cjs | 256 +++++++++++++++++++++ 8 files changed, 873 insertions(+), 1 deletion(-) create mode 100644 scripts/testE2E.js create mode 100644 tests/e2e/README.md create mode 100644 tests/e2e/package.test.cjs create mode 100644 tests/e2e/resources.test.cjs create mode 100644 tests/e2e/transport.test.cjs diff --git a/.github/workflows/pull-reqeust.yml b/.github/workflows/pull-reqeust.yml index f6129e35..e33cc73c 100644 --- a/.github/workflows/pull-reqeust.yml +++ b/.github/workflows/pull-reqeust.yml @@ -29,6 +29,9 @@ jobs: - name: Check CommonJS and ESM package imports run: npm run test:package + - name: Run packed SDK end-to-end tests + run: npm run test:e2e + - name: Run lint checks run: npm run lint:ci diff --git a/jest.config.js b/jest.config.js index b3785f22..927675a7 100644 --- a/jest.config.js +++ b/jest.config.js @@ -29,6 +29,7 @@ const config = { statements: 80, }, }, + testPathIgnorePatterns: ['/node_modules/', '/tests/e2e/'], clearMocks: true, collectCoverage: true, coverageReporters: ['text', 'cobertura'], diff --git a/package.json b/package.json index b352023a..5ad222aa 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,8 @@ "prepare": "npm run build", "build:docs": "typedoc --out docs", "version": "npm run export-version && git add src/version.ts", - "test:package": "node scripts/testPackage.js" + "test:package": "node scripts/testPackage.js", + "test:e2e": "node scripts/testE2E.js" }, "keywords": [ "email", diff --git a/scripts/testE2E.js b/scripts/testE2E.js new file mode 100644 index 00000000..5650146f --- /dev/null +++ b/scripts/testE2E.js @@ -0,0 +1,76 @@ +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { spawnSync } = require('node:child_process'); + +const root = path.join(__dirname, '..'); +const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm'; + +function run(command, args, options = {}) { + const result = spawnSync(command, args, { + cwd: root, + stdio: 'inherit', + ...options, + }); + if (result.error || result.status !== 0) { + throw new Error('End-to-end test command failed.'); + } + return result.stdout; +} + +const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nylas-sdk-e2e-')); +try { + run(npm, ['run', 'build']); + const packed = JSON.parse( + run( + npm, + ['pack', '--ignore-scripts', '--json', '--pack-destination', tempDir], + { encoding: 'utf8', stdio: ['ignore', 'pipe', 'inherit'] } + ) + ); + const filename = packed[0]?.filename; + if (typeof filename !== 'string' || path.basename(filename) !== filename) { + throw new Error('Unable to locate the packed SDK artifact.'); + } + + const consumerDir = path.join(tempDir, 'consumer'); + fs.mkdirSync(consumerDir); + fs.writeFileSync( + path.join(consumerDir, 'package.json'), + JSON.stringify({ name: 'nylas-e2e-consumer', private: true }) + ); + run( + npm, + [ + 'install', + '--ignore-scripts', + '--no-audit', + '--no-fund', + '--package-lock=false', + '--loglevel=error', + path.join(tempDir, filename), + ], + { cwd: consumerDir } + ); + + const testsDir = path.join(root, 'tests', 'e2e'); + const tests = fs + .readdirSync(testsDir) + .filter((name) => name.endsWith('.test.cjs')) + .sort() + .map((name) => path.join(testsDir, name)); + if (tests.length === 0) { + throw new Error('No end-to-end tests found.'); + } + process.stdout.write( + `Running packed SDK end-to-end tests on ${process.version}\n` + ); + run(process.execPath, ['--test', ...tests], { + env: { ...process.env, NYLAS_E2E_CONSUMER_DIR: consumerDir }, + }); +} catch { + console.error('Packed SDK end-to-end checks failed.'); + process.exitCode = 1; +} finally { + fs.rmSync(tempDir, { recursive: true, force: true }); +} diff --git a/tests/e2e/README.md b/tests/e2e/README.md new file mode 100644 index 00000000..9d772e1e --- /dev/null +++ b/tests/e2e/README.md @@ -0,0 +1,15 @@ +Run the packed SDK end-to-end suite with: + +```sh +npm run test:e2e +``` + +The runner builds the SDK, creates an npm tarball, installs it into a temporary +consumer project, and tests the installed package against local HTTP servers. +CommonJS and ESM consumer programs are compiled and executed from that project. +No Nylas credentials are required. Installation scripts are disabled, and the +temporary project is removed after the run. + +These tests use Node's built-in test runner and native HTTP/fetch behavior. Jest +excludes this directory so its fetch mocks cannot affect these checks. The pull +request workflow runs the suite on every supported Node.js version in its matrix. diff --git a/tests/e2e/package.test.cjs b/tests/e2e/package.test.cjs new file mode 100644 index 00000000..ad8e7400 --- /dev/null +++ b/tests/e2e/package.test.cjs @@ -0,0 +1,174 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const http = require('node:http'); +const path = require('node:path'); +const { createRequire } = require('node:module'); +const { spawnSync } = require('node:child_process'); +const { test } = require('node:test'); +const ts = require('typescript'); + +const consumerDir = process.env.NYLAS_E2E_CONSUMER_DIR; +assert(consumerDir, 'Run this suite with npm run test:e2e'); +const consumerRequire = createRequire(path.join(consumerDir, 'package.json')); +const Nylas = consumerRequire('nylas'); + +test('installed SDK reads filename-free attachment metadata over HTTP', async (t) => { + const requests = []; + const attachment = { + id: 'mime-part', + grant_id: 'grant-id', + content_type: 'message/delivery-status', + size: 10, + }; + const server = http.createServer((req, res) => { + requests.push({ method: req.method, url: req.url }); + res.setHeader('content-type', 'application/json'); + if (req.url.startsWith('/v3/grants/grant-id/attachments/mime-part?')) { + res.end( + JSON.stringify({ request_id: 'attachment-request', data: attachment }) + ); + } else if (req.url === '/v3/grants/grant-id/messages/message-id') { + res.end( + JSON.stringify({ + request_id: 'message-request', + data: { id: 'message-id', attachments: [attachment] }, + }) + ); + } else { + res.statusCode = 404; + res.end( + JSON.stringify({ error: { type: 'not_found', message: 'Not found.' } }) + ); + } + }); + t.after(() => { + server.closeAllConnections(); + return new Promise((resolve) => server.close(resolve)); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const client = new Nylas({ + apiKey: 'e2e-key', + apiUri: `http://127.0.0.1:${server.address().port}`, + timeout: 5, + }); + + const metadata = await client.attachments.find({ + identifier: 'grant-id', + attachmentId: 'mime-part', + queryParams: { messageId: 'message-id' }, + }); + assert.equal(metadata.requestId, 'attachment-request'); + assert.deepEqual(metadata.data, { + id: 'mime-part', + grantId: 'grant-id', + contentType: 'message/delivery-status', + size: 10, + }); + assert.equal(Object.hasOwn(metadata.data, 'filename'), false); + + const message = await client.messages.find({ + identifier: 'grant-id', + messageId: 'message-id', + }); + assert.deepEqual(message.data.attachments, [metadata.data]); + assert.deepEqual(requests, [ + { + method: 'GET', + url: '/v3/grants/grant-id/attachments/mime-part?message_id=message-id', + }, + { method: 'GET', url: '/v3/grants/grant-id/messages/message-id' }, + ]); +}); + +test('installed package compiles and runs CommonJS and ESM consumers', () => { + const common = `import assert from 'node:assert/strict'; +import Nylas, { + Attachment, + AttachmentReference, + SendAttachmentRequest, + CreateAttachmentRequest, + NylasApiError, + NylasOAuthError, + NylasSdkTimeoutError, + WhenType, +} from 'nylas'; +const client: Nylas = new Nylas({ apiKey: 'e2e-key' }); +const attachment: Attachment = { + id: 'mime-part', grantId: 'grant-id', contentType: 'message/delivery-status', +}; +const reference: AttachmentReference = { id: 'upload-id' }; +const sendAttachment: SendAttachmentRequest = reference; +void sendAttachment; +const filename: string | undefined = attachment.filename; +assert.equal(filename, undefined); +assert.equal(typeof client.messages.find, 'function'); +assert.equal(typeof NylasOAuthError, 'function'); +assert.equal(typeof NylasSdkTimeoutError, 'function'); +assert.equal(typeof WhenType, 'object'); +const error: NylasApiError = new NylasApiError({ + requestId: 'request-id', error: { type: 'e2e', message: 'Example.' }, +}); +assert(error instanceof NylasApiError); +// @ts-expect-error Outgoing attachment content still requires a filename. +const invalidUpload: CreateAttachmentRequest = { contentType: 'text/plain', content: 'eA==' }; +void invalidUpload; +`; + const files = [ + path.join(consumerDir, 'consumer.cts'), + path.join(consumerDir, 'consumer.mts'), + ]; + fs.writeFileSync( + files[0], + `${common}\nimport NylasConstructor = require('nylas'); +const classicClient: NylasConstructor = new NylasConstructor({ apiKey: 'e2e-key' }); +const defaultClient: NylasConstructor = new NylasConstructor.default({ apiKey: 'e2e-key' }); +assert(classicClient instanceof NylasConstructor); +assert(defaultClient instanceof NylasConstructor); +assert.equal(NylasConstructor.NylasApiError, NylasApiError); +` + ); + fs.writeFileSync(files[1], common); + + for (const [module, moduleResolution] of [ + [ts.ModuleKind.Node16, ts.ModuleResolutionKind.Node16], + [ts.ModuleKind.NodeNext, ts.ModuleResolutionKind.NodeNext], + [ts.ModuleKind.Preserve, ts.ModuleResolutionKind.Bundler], + ]) { + const emit = module === ts.ModuleKind.NodeNext; + const program = ts.createProgram(files, { + module, + moduleResolution, + target: ts.ScriptTarget.ES2022, + strict: true, + noEmit: !emit, + outDir: path.join(consumerDir, 'compiled'), + esModuleInterop: true, + // formdata-node has an existing Node16 transitive declaration conflict. + skipLibCheck: moduleResolution === ts.ModuleResolutionKind.Node16, + types: ['node'], + typeRoots: [path.join(__dirname, '..', '..', 'node_modules', '@types')], + }); + const diagnostics = ts.getPreEmitDiagnostics(program); + assert.equal( + diagnostics.length, + 0, + ts.formatDiagnosticsWithColorAndContext(diagnostics, { + getCanonicalFileName: (filename) => filename, + getCurrentDirectory: () => consumerDir, + getNewLine: () => '\n', + }) + ); + if (emit) { + assert.equal(program.emit().emitSkipped, false); + } + } + + for (const filename of ['consumer.cjs', 'consumer.mjs']) { + const result = spawnSync( + process.execPath, + [path.join(consumerDir, 'compiled', filename)], + { cwd: consumerDir, encoding: 'utf8' } + ); + assert.equal(result.status, 0, result.stderr); + } +}); diff --git a/tests/e2e/resources.test.cjs b/tests/e2e/resources.test.cjs new file mode 100644 index 00000000..d40b8eaf --- /dev/null +++ b/tests/e2e/resources.test.cjs @@ -0,0 +1,346 @@ +const assert = require('node:assert/strict'); +const http = require('node:http'); +const { createRequire } = require('node:module'); +const path = require('node:path'); +const { Readable } = require('node:stream'); +const { test } = require('node:test'); + +const consumerRequire = createRequire( + path.join(process.env.NYLAS_E2E_CONSUMER_DIR, 'package.json') +); +const Nylas = consumerRequire('nylas'); +const JSON_LIMIT = 3 * 1024 * 1024; +const UPLOADED_ID = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890'; + +async function withServer(run) { + const requests = []; + const server = http.createServer(async (req, res) => { + const chunks = []; + for await (const chunk of req) chunks.push(chunk); + requests.push({ + method: req.method, + url: new URL(req.url, `http://${req.headers.host}`), + headers: req.headers, + body: Buffer.concat(chunks), + }); + + let data = { id: 'fixture-message' }; + if (req.method === 'GET') data = []; + if (req.url.endsWith('/attachment-uploads')) { + data = { + attachment_id: UPLOADED_ID, + method: 'PUT', + url: `http://${req.headers.host}/upload`, + headers: { 'Content-Type': 'application/octet-stream' }, + expires_at: '2099-01-01T00:00:00Z', + max_size: 157286400, + size: 10, + content_type: 'application/octet-stream', + filename: 'upload.bin', + grant_id: 'grant', + }; + } else if (req.url.endsWith('/complete')) { + data = { attachment_id: UPLOADED_ID, grant_id: 'grant', status: 'ready' }; + } + + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ request_id: 'fixture-request', data })); + }); + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(0, '127.0.0.1', resolve); + }); + const apiUri = `http://127.0.0.1:${server.address().port}`; + + try { + await run(new Nylas({ apiKey: 'loopback-test-only', apiUri }), requests); + } finally { + await new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())); + server.closeAllConnections(); + }); + } +} + +async function multipart(request) { + assert.match( + request.headers['content-type'], + /^multipart\/form-data; boundary=/ + ); + return new Response(request.body, { + headers: { 'Content-Type': request.headers['content-type'] }, + }).formData(); +} + +async function invoke(client, operation, requestBody) { + if (operation === 'message send') { + return client.messages.send({ identifier: 'grant', requestBody }); + } + if (operation === 'draft create') { + return client.drafts.create({ identifier: 'grant', requestBody }); + } + if (operation === 'draft update') { + return client.drafts.update({ + identifier: 'grant', + draftId: 'draft', + requestBody, + }); + } + return client.transactionalSend.send({ + domainName: 'example.com', + requestBody, + }); +} + +test('draft anyEmail reaches HTTP as one comma-separated value without mutating input', async () => { + await withServer(async (client, requests) => { + const queryParams = Object.freeze({ + anyEmail: Object.freeze(['first@example.com', 'second@example.com']), + subject: 'Report', + }); + await client.drafts.list({ identifier: 'grant', queryParams }); + + assert.equal(requests.length, 1); + assert.equal(requests[0].method, 'GET'); + assert.equal(requests[0].url.pathname, '/v3/grants/grant/drafts'); + assert.deepEqual(requests[0].url.searchParams.getAll('any_email'), [ + 'first@example.com,second@example.com', + ]); + assert.equal(requests[0].url.searchParams.get('subject'), 'Report'); + assert.deepEqual(queryParams.anyEmail, [ + 'first@example.com', + 'second@example.com', + ]); + }); +}); + +test('message and draft upload payloads preserve actual bytes through the packed SDK', async (t) => { + const operations = [ + 'message send', + 'draft create', + 'draft update', + 'transactional send', + ]; + const cases = [ + ['buffer', (bytes) => bytes], + ['base64', (bytes) => bytes.toString('base64')], + ['stream without size', (bytes) => Readable.from([bytes])], + [ + 'stream with size', + (bytes) => Readable.from([bytes]), + (bytes) => ({ size: bytes.length }), + ], + ]; + + for (const operation of operations) { + for (const [name, makeContent, extraFields] of cases) { + await t.test( + `${operation}: ${name} over 3MiB uses multipart with intact bytes`, + async () => { + await withServer(async (client, requests) => { + const expected = Buffer.alloc(JSON_LIMIT + 17, 0xab); + await invoke(client, operation, { + to: [{ email: 'test@example.com' }], + subject: 'Multipart bytes', + attachments: [ + { + filename: 'payload.bin', + contentType: 'application/octet-stream', + content: makeContent(expected), + ...extraFields?.(expected), + }, + ], + }); + + assert.equal(requests.length, 1); + const form = await multipart(requests[0]); + assert.equal( + JSON.parse(form.get('message')).subject, + 'Multipart bytes' + ); + assert.equal(form.get('file0').name, 'payload.bin'); + assert.deepEqual( + Buffer.from(await form.get('file0').arrayBuffer()), + expected + ); + }); + } + ); + } + } +}); + +test('base64 expansion selects multipart before a raw Buffer reaches 3MiB', async () => { + await withServer(async (client, requests) => { + const expected = Buffer.alloc(Math.floor(2.4 * 1024 * 1024), 0xcc); + await client.messages.send({ + identifier: 'grant', + requestBody: { + to: [{ email: 'test@example.com' }], + attachments: [ + { + filename: 'expanded.bin', + contentType: 'application/octet-stream', + content: expected, + size: 1, + }, + ], + }, + }); + const form = await multipart(requests[0]); + assert.deepEqual( + Buffer.from(await form.get('file0').arrayBuffer()), + expected + ); + }); +}); + +test('small binary content uses JSON with correct base64 bytes', async () => { + await withServer(async (client, requests) => { + const expected = Buffer.from([0, 1, 2, 253, 254, 255]); + await client.messages.send({ + identifier: 'grant', + requestBody: { + to: [{ email: 'test@example.com' }], + attachments: [ + { + filename: 'small.bin', + contentType: 'application/octet-stream', + content: expected, + }, + ], + }, + }); + assert.match(requests[0].headers['content-type'], /^application\/json/); + const body = JSON.parse(requests[0].body); + assert.deepEqual( + Buffer.from(body.attachments[0].content, 'base64'), + expected + ); + assert.equal(body.attachments[0].content_type, 'application/octet-stream'); + }); +}); + +test('completed upload references survive JSON and multipart send and draft requests', async (t) => { + for (const operation of ['message send', 'draft create', 'draft update']) { + await t.test( + `${operation}: ID-only reference reaches JSON without invented file metadata`, + async () => { + await withServer(async (client, requests) => { + await invoke(client, operation, { + to: [{ email: 'test@example.com' }], + body: '', + attachments: [{ id: UPLOADED_ID, contentId: 'chart1' }], + }); + assert.match( + requests[0].headers['content-type'], + /^application\/json/ + ); + assert.deepEqual(JSON.parse(requests[0].body).attachments, [ + { id: UPLOADED_ID, content_id: 'chart1' }, + ]); + }); + } + ); + await t.test( + `${operation}: multipart keeps uploaded references and binary files`, + async () => { + await withServer(async (client, requests) => { + const expected = Buffer.alloc(JSON_LIMIT + 1, 0xdd); + await invoke(client, operation, { + to: [{ email: 'test@example.com' }], + attachments: [ + { id: UPLOADED_ID, contentId: 'chart1' }, + { + filename: 'extra.bin', + contentType: 'application/octet-stream', + content: expected, + }, + ], + }); + const form = await multipart(requests[0]); + assert.deepEqual(JSON.parse(form.get('message')).attachments, [ + { id: UPLOADED_ID, content_id: 'chart1' }, + ]); + assert.deepEqual([...form.keys()], ['message', 'file1']); + assert.deepEqual( + Buffer.from(await form.get('file1').arrayBuffer()), + expected + ); + }); + } + ); + } +}); + +test('invalid uploaded references fail before any HTTP request', async () => { + await withServer(async (client, requests) => { + for (const reference of [ + {}, + { id: '' }, + { id: '../attachment' }, + { id: 'a'.repeat(256) }, + { id: UPLOADED_ID, contentId: 'unsafe\r\nvalue' }, + { id: UPLOADED_ID, filename: 'unexpected.bin' }, + ]) { + await assert.rejects( + client.messages.send({ + identifier: 'grant', + requestBody: { + to: [{ email: 'test@example.com' }], + attachments: [reference], + }, + }), + /Invalid attachment reference\./ + ); + } + assert.equal(requests.length, 0); + }); +}); + +test('public upload-session flow can send its completed ID without SDK or fetch mocks', async () => { + await withServer(async (client, requests) => { + const bytes = Buffer.from('file bytes'); + const created = await client.attachments.createUploadSession({ + identifier: 'grant', + requestBody: { + filename: 'upload.bin', + contentType: 'application/octet-stream', + size: bytes.length, + }, + }); + const uploaded = await fetch(created.data.url, { + method: created.data.method, + headers: created.data.headers, + body: bytes, + }); + assert.equal(uploaded.status, 200); + const completed = await client.attachments.completeUploadSession({ + identifier: 'grant', + attachmentId: created.data.attachmentId, + }); + assert.equal(completed.data.status, 'ready'); + await client.messages.send({ + identifier: 'grant', + requestBody: { + to: [{ email: 'test@example.com' }], + attachments: [{ id: completed.data.attachmentId }], + }, + }); + + assert.deepEqual( + requests.map((request) => [request.method, request.url.pathname]), + [ + ['POST', '/v3/grants/grant/attachment-uploads'], + ['PUT', '/upload'], + ['POST', `/v3/grants/grant/attachment-uploads/${UPLOADED_ID}/complete`], + ['POST', '/v3/grants/grant/messages/send'], + ] + ); + assert.deepEqual(requests[1].body, bytes); + assert.equal(requests[1].headers.authorization, undefined); + assert.deepEqual(JSON.parse(requests[3].body).attachments, [ + { id: UPLOADED_ID }, + ]); + }); +}); diff --git a/tests/e2e/transport.test.cjs b/tests/e2e/transport.test.cjs new file mode 100644 index 00000000..44253636 --- /dev/null +++ b/tests/e2e/transport.test.cjs @@ -0,0 +1,256 @@ +const assert = require('node:assert/strict'); +const http = require('node:http'); +const path = require('node:path'); +const { createRequire } = require('node:module'); +const test = require('node:test'); + +const consumerRequire = createRequire( + path.join(process.env.NYLAS_E2E_CONSUMER_DIR, 'package.json') +); +const Nylas = consumerRequire('nylas'); + +async function fixture(t, handler, timeout = 1) { + const timers = new Set(); + const later = (callback, delay) => { + const timer = setTimeout(callback, delay); + timers.add(timer); + }; + const server = http.createServer((request, response) => { + handler(request, response, later); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + t.after(async () => { + for (const timer of timers) clearTimeout(timer); + server.closeAllConnections(); + await new Promise((resolve) => server.close(resolve)); + }); + return new Nylas({ + apiKey: 'e2e-fixture-key', + apiUri: `http://127.0.0.1:${server.address().port}`, + timeout, + }); +} + +async function bounded(promise) { + let timer; + try { + return await Promise.race([ + promise, + new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error('E2E request did not settle')), + 2000 + ); + }), + ]); + } finally { + clearTimeout(timer); + } +} + +const downloadParams = { + identifier: 'me', + attachmentId: 'attachment-id', + queryParams: { messageId: 'message-id' }, +}; + +for (const kind of ['json', 'binary']) { + test(`terminated ${kind} response bodies expose typed errors and request context`, async (t) => { + const client = await fixture(t, (_request, response, later) => { + response.writeHead(200, { + 'Content-Type': + kind === 'json' ? 'application/json' : 'application/octet-stream', + 'Content-Length': '1000', + 'x-request-id': 'terminated-request', + 'x-fastly-id': 'terminated-flow', + }); + response.flushHeaders(); + response.write(kind === 'json' ? '{"data":' : 'partial-binary-data'); + later(() => response.destroy(), 40); + }); + const request = + kind === 'json' + ? client.messages.find({ identifier: 'me', messageId: 'message-id' }) + : client.attachments.downloadBytes(downloadParams); + + await assert.rejects(bounded(request), (error) => { + assert.ok(error instanceof Nylas.NylasApiError); + assert.equal(error.type, 'sdk.response_body_error'); + assert.equal(error.requestId, 'terminated-request'); + assert.equal(error.flowId, 'terminated-flow'); + assert.equal(error.statusCode, 200); + assert.equal(error.headers['x-request-id'], 'terminated-request'); + return true; + }); + }); +} + +for (const kind of ['json', 'binary', 'error']) { + test(`stalled ${kind} response bodies respect the configured timeout`, async (t) => { + const client = await fixture( + t, + (_request, response) => { + response.writeHead(kind === 'error' ? 503 : 200, { + 'Content-Type': 'application/json', + 'x-request-id': 'timeout-request', + 'x-fastly-id': 'timeout-flow', + }); + response.flushHeaders(); + response.write(kind === 'binary' ? 'partial-binary-data' : '{"data":'); + }, + 0.1 + ); + const request = + kind === 'binary' + ? client.attachments.downloadBytes(downloadParams) + : client.messages.find({ identifier: 'me', messageId: 'message-id' }); + + await assert.rejects(bounded(request), (error) => { + assert.ok(error instanceof Nylas.NylasSdkTimeoutError); + assert.equal(error.timeout, 0.1); + assert.equal(error.requestId, 'timeout-request'); + assert.equal(error.flowId, 'timeout-flow'); + return true; + }); + }); +} + +test('stream handoff permits caller-owned reads beyond the request timeout', async (t) => { + const client = await fixture( + t, + (_request, response, later) => { + response.writeHead(200, { 'Content-Type': 'application/octet-stream' }); + response.flushHeaders(); + response.write('first-'); + later(() => response.end('last'), 180); + }, + 0.1 + ); + + const stream = await client.attachments.download(downloadParams); + const reader = stream.getReader(); + const chunks = []; + await bounded( + (async () => { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + chunks.push(Buffer.from(value)); + } + })() + ); + assert.equal(Buffer.concat(chunks).toString(), 'first-last'); +}); + +test('rules list preserves every nested page and remaining cursor over real HTTP', async (t) => { + const requests = []; + const client = await fixture(t, (request, response) => { + const url = new URL(request.url, 'http://fixture'); + requests.push(url); + const pageToken = url.searchParams.get('page_token'); + const page = pageToken ? Number(pageToken.replace('cursor-', '')) : 1; + response.setHeader('Content-Type', 'application/json'); + response.end( + JSON.stringify({ + request_id: `request-${page}`, + data: { + items: [{ id: `rule-${page}`, name: `Rule ${page}` }], + next_cursor: `cursor-${page + 1}`, + }, + }) + ); + }); + + const result = await bounded( + client.rules.list({ queryParams: { limit: 3 } }) + ); + assert.deepEqual( + result.data.map((rule) => rule.id), + ['rule-1', 'rule-2', 'rule-3'] + ); + assert.equal(result.requestId, 'request-3'); + assert.equal(result.nextCursor, 'cursor-4'); + assert.deepEqual( + requests.map((url) => url.pathname), + ['/v3/rules', '/v3/rules', '/v3/rules'] + ); + assert.deepEqual( + requests.map((url) => url.searchParams.get('limit')), + ['3', '2', '1'] + ); + assert.deepEqual( + requests.map((url) => url.searchParams.get('page_token')), + [null, 'cursor-2', 'cursor-3'] + ); +}); + +test('public JSON resource methods preserve nulls and nested arrays in both directions', async (t) => { + let wirePayload; + const client = await fixture(t, (request, response) => { + const chunks = []; + request.on('data', (chunk) => chunks.push(chunk)); + request.on('end', () => { + wirePayload = JSON.parse(Buffer.concat(chunks).toString()); + response.setHeader('Content-Type', 'application/json'); + response.end( + JSON.stringify({ request_id: 'array-request', data: wirePayload }) + ); + }); + }); + const requestBody = { + title: 'Transport fixture', + when: { startTime: 1, endTime: 2 }, + // Extension data deliberately exercises recursive serialization through a public method. + customData: [null, [{ nestedKey: 'value' }, null, ['value', 7]], []], + metadata: { Keep_Exact: [null, [{ Keep_Inner: 'value' }]] }, + }; + const result = await bounded( + client.events.create({ + identifier: 'me', + queryParams: { calendarId: 'calendar-id' }, + requestBody, + }) + ); + + assert.deepEqual(wirePayload.custom_data, [ + null, + [{ nested_key: 'value' }, null, ['value', 7]], + [], + ]); + assert.deepEqual(wirePayload.when, { start_time: 1, end_time: 2 }); + assert.deepEqual(wirePayload.metadata, requestBody.metadata); + assert.deepEqual(result.data, requestBody); +}); + +for (const status of [200, 502]) { + test(`malformed HTTP ${status} responses do not expose their body in errors`, async (t) => { + const body = '{"private_fixture_content":"do-not-expose"} invalid-json'; + const client = await fixture(t, (_request, response) => { + response.writeHead(status, { + 'Content-Type': 'application/json', + 'x-request-id': 'parse-request', + 'x-fastly-id': 'parse-flow', + }); + response.end(body); + }); + + await assert.rejects( + bounded( + client.messages.find({ + identifier: 'me', + messageId: 'message-id', + }) + ), + (error) => { + assert.ok(error instanceof Nylas.NylasApiError); + assert.equal(error.type, 'sdk.response_parse_error'); + assert.equal(error.requestId, 'parse-request'); + assert.equal(error.flowId, 'parse-flow'); + assert.equal(error.statusCode, status); + assert.ok(!error.message.includes('private_fixture_content')); + assert.ok(!error.message.includes('do-not-expose')); + return true; + } + ); + }); +} From 3d267ee63e72c4f30eafffc9af07c60ca8dff931 Mon Sep 17 00:00:00 2001 From: Aaron de Mello Date: Wed, 4 Nov 2026 15:24:16 -0500 Subject: [PATCH 2/6] NYL-469 verify ambiguous references never reach HTTP --- tests/e2e/resources.test.cjs | 37 ++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/tests/e2e/resources.test.cjs b/tests/e2e/resources.test.cjs index d40b8eaf..6e0896f8 100644 --- a/tests/e2e/resources.test.cjs +++ b/tests/e2e/resources.test.cjs @@ -298,6 +298,43 @@ test('invalid uploaded references fail before any HTTP request', async () => { }); }); +test('ambiguous uploaded references fail before JSON or multipart HTTP requests across resource methods', async (t) => { + for (const operation of [ + 'message send', + 'draft create', + 'draft update', + 'transactional send', + ]) { + for (const largeBody of [false, true]) { + await t.test( + `${operation}: ${largeBody ? 'large' : 'small'} payload rejects ambiguous references`, + async () => { + await withServer(async (client, requests) => { + for (const reference of [ + { id: '../invalid-reference', content: undefined }, + { id: UPLOADED_ID, unexpected: undefined }, + { id: UPLOADED_ID, content: Buffer.from('content') }, + Object.defineProperty({ id: UPLOADED_ID }, 'content', { + value: undefined, + }), + ]) { + await assert.rejects( + invoke(client, operation, { + to: [{ email: 'test@example.test' }], + body: largeBody ? 'x'.repeat(JSON_LIMIT) : 'Small body', + attachments: [reference], + }), + /Invalid attachment reference\./ + ); + assert.equal(requests.length, 0); + } + }); + } + ); + } + } +}); + test('public upload-session flow can send its completed ID without SDK or fetch mocks', async () => { await withServer(async (client, requests) => { const bytes = Buffer.from('file bytes'); From fff6a264cd46a6aa69233a37c0aa516ade51ebcb Mon Sep 17 00:00:00 2001 From: Aaron de Mello Date: Wed, 4 Nov 2026 15:24:14 -0500 Subject: [PATCH 3/6] test: add opt-in live test-account SDK regressions --- scripts/testLiveE2E.js | 580 ++++++++++++++++++++++++++ tests/e2e/LIVE.md | 47 +++ tests/e2e/live-runner-safety.test.cjs | 134 ++++++ 3 files changed, 761 insertions(+) create mode 100644 scripts/testLiveE2E.js create mode 100644 tests/e2e/LIVE.md create mode 100644 tests/e2e/live-runner-safety.test.cjs diff --git a/scripts/testLiveE2E.js b/scripts/testLiveE2E.js new file mode 100644 index 00000000..9d00987b --- /dev/null +++ b/scripts/testLiveE2E.js @@ -0,0 +1,580 @@ +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { parseEnv } = require('node:util'); +const { createRequire } = require('node:module'); +const { randomUUID, createHash } = require('node:crypto'); +const { Readable } = require('node:stream'); +const { spawnSync } = require('node:child_process'); + +const root = path.join(__dirname, '..'); +const allowedApis = new Set([ + 'https://api.us.nylas.com', + 'https://api.eu.nylas.com', +]); +const mimeType = 'application/octet-stream'; +let currentCase = 'configuration'; +let failed = false; + +function check(condition) { + if (!condition) throw new Error('Live end-to-end check failed.'); +} + +function statusCode(error) { + const code = error?.statusCode; + return Number.isInteger(code) && code >= 100 && code <= 599 + ? code + : undefined; +} + +function report(result, name, error) { + const status = statusCode(error); + process.stdout.write( + `${result} ${name}${status ? ` status=${status}` : ''}\n` + ); + if (result === 'FAIL') failed = true; +} + +async function step(name, action) { + currentCase = name; + const result = await action(); + report('PASS', name); + return result; +} + +function configFromFile(filename) { + const stat = fs.statSync(filename); + check(stat.isFile() && stat.size > 0 && stat.size <= 65536); + const values = parseEnv(fs.readFileSync(filename, 'utf8')); + const config = { + apiKey: values.NYLAS_API_KEY, + apiUri: values.NYLAS_API_URI || 'https://api.us.nylas.com', + grantId: values.NYLAS_GRANT_ID, + recipient: values.TEST_EMAIL, + }; + check( + typeof config.apiKey === 'string' && + /^[\x21-\x7e]{8,8192}$/.test(config.apiKey) + ); + check(allowedApis.has(config.apiUri)); + check( + typeof config.grantId === 'string' && + /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(config.grantId) + ); + check( + typeof config.recipient === 'string' && + config.recipient.length <= 254 && + /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,63}$/.test( + config.recipient + ) + ); + return config; +} + +function opaqueId(value) { + check(typeof value === 'string' && /^[\x21-\x7e]{1,2048}$/.test(value)); + return value; +} + +function requireSameBytes(actual, expected) { + check(Buffer.isBuffer(actual) && actual.length === expected.length); + const digest = (value) => createHash('sha256').update(value).digest('hex'); + check(digest(actual) === digest(expected)); +} + +function buildInstalledPackage(tempDir) { + const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm'; + const env = { ...process.env }; + for (const name of Object.keys(env)) { + if (name.startsWith('NYLAS_') || name === 'TEST_EMAIL') delete env[name]; + } + const run = (args, cwd = root) => { + const result = spawnSync(npm, args, { + cwd, + env, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], + timeout: 180000, + maxBuffer: 4 * 1024 * 1024, + }); + check(!result.error && result.status === 0); + return result.stdout; + }; + run(['run', 'build']); + const packed = JSON.parse( + run(['pack', '--ignore-scripts', '--json', '--pack-destination', tempDir]) + ); + const filename = packed[0]?.filename; + check(typeof filename === 'string' && path.basename(filename) === filename); + const consumerDir = path.join(tempDir, 'consumer'); + fs.mkdirSync(consumerDir); + fs.writeFileSync( + path.join(consumerDir, 'package.json'), + JSON.stringify({ name: 'nylas-live-e2e-consumer', private: true }) + ); + run( + [ + 'install', + '--ignore-scripts', + '--no-audit', + '--no-fund', + '--package-lock=false', + '--loglevel=error', + path.join(tempDir, filename), + ], + consumerDir + ); + return createRequire(path.join(consumerDir, 'package.json'))('nylas'); +} + +const transientStatuses = new Set([404, 409, 429, 500, 502, 503, 504]); +async function poll(read, matches, attempts = 8) { + for (let attempt = 0; attempt < attempts; attempt++) { + try { + const result = await read(); + if (matches(result)) return result; + } catch (error) { + if (!transientStatuses.has(statusCode(error))) throw error; + if (attempt === attempts - 1) throw error; + } + if (attempt < attempts - 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + } + } + throw new Error('Live consistency deadline exceeded.'); +} + +function selfRecipient(object, email) { + return ( + Array.isArray(object?.to) && + object.to.some((item) => item.email?.toLowerCase() === email.toLowerCase()) + ); +} + +async function validateDownload(client, config, object, bytes, filename, name) { + const attachments = object.attachments; + if (!Array.isArray(attachments) || !attachments.some((item) => item.id)) { + report('SKIP', `${name}-attachment-id-unavailable`); + return; + } + const attachment = attachments.find((item) => item.filename === filename); + check(attachment); + const attachmentId = opaqueId(attachment.id); + await step(`${name}-download-integrity`, async () => { + const download = await poll( + () => + client.attachments.downloadBytes({ + identifier: config.grantId, + attachmentId, + queryParams: { messageId: opaqueId(object.id) }, + }), + (result) => Buffer.isBuffer(result) + ); + requireSameBytes(download, bytes); + }); +} + +function validateUploadSession(session, config, bytes, filename) { + check(session && typeof session === 'object'); + check( + typeof session.attachmentId === 'string' && + /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test( + session.attachmentId + ) + ); + check(session.method === 'PUT' && session.grantId === config.grantId); + check(session.filename === filename && session.contentType === mimeType); + check(session.size === bytes.length); + check( + Number.isSafeInteger(session.maxSize) && + session.maxSize >= bytes.length && + session.maxSize <= 157286400 + ); + const expiry = Date.parse(session.expiresAt); + check(expiry > Date.now() && expiry <= Date.now() + 2 * 60 * 60 * 1000); + check(typeof session.url === 'string' && session.url.length <= 16384); + check( + typeof session.expiresAt === 'string' && session.expiresAt.length <= 64 + ); + const url = new URL(session.url); + check( + url.protocol === 'https:' && + url.hostname === 'storage.googleapis.com' && + (url.port === '' || url.port === '443') && + url.username === '' && + url.password === '' && + url.hash === '' && + url.pathname.startsWith('/upload/storage/v1/b/') && + url.searchParams.get('uploadType') === 'resumable' && + (url.searchParams.get('upload_id') || '').length >= 8 + ); + check( + session.headers && + typeof session.headers === 'object' && + !Array.isArray(session.headers) && + Object.keys(session.headers).length <= 2 + ); + const headers = new Headers(); + for (const [name, value] of Object.entries(session.headers)) { + check(['content-type', 'content-length'].includes(name.toLowerCase())); + check( + typeof value === 'string' && value.length <= 1024 && !/[\r\n]/.test(value) + ); + headers.set(name, value); + } + check(headers.get('content-type') === mimeType); + check( + !headers.has('content-length') || + headers.get('content-length') === String(bytes.length) + ); + check(!headers.has('authorization') && !headers.has('cookie')); + return { url, headers }; +} + +async function runProviderChecks(Nylas, config, verifyOnly) { + const client = new Nylas({ + apiKey: config.apiKey, + apiUri: config.apiUri, + timeout: 30, + }); + const grant = await step('test-account-preflight', async () => { + const result = await client.grants.find({ grantId: config.grantId }); + check( + result.data?.id === config.grantId && result.data.grantStatus === 'valid' + ); + check( + typeof result.data.email === 'string' && + result.data.email.toLowerCase() === config.recipient.toLowerCase() + ); + return result.data; + }); + if (verifyOnly) return; + + const drafts = new Set(); + const messages = new Set(); + const draftSubjects = new Set(); + const messageSubjects = new Set(); + const createBody = (subject, attachment) => ({ + to: [{ email: config.recipient }], + subject, + body: 'Synthetic Node.js SDK end-to-end test. Safe to delete.', + attachments: [attachment], + }); + const discover = async (resource, subjects, ids) => { + for (const subject of subjects) { + const result = await resource.list({ + identifier: config.grantId, + queryParams: { subject, anyEmail: [config.recipient], limit: 20 }, + }); + check(Array.isArray(result.data) && !result.nextCursor); + for (const item of result.data) { + if (item.subject === subject && selfRecipient(item, config.recipient)) { + ids.add(opaqueId(item.id)); + } + } + } + }; + const cleanup = async () => { + for (const [name, resource, ids, subjects, idKey] of [ + ['draft', client.drafts, drafts, draftSubjects, 'draftId'], + ['message', client.messages, messages, messageSubjects, 'messageId'], + ]) { + if (!ids.size && !subjects.size) continue; + // Revisit exact synthetic subjects to catch a late self-delivery or an + // ambiguous POST outcome. No unrelated message is eligible for deletion. + for (let round = 0; round < 3; round++) { + try { + await discover(resource, subjects, ids); + } catch (error) { + report('FAIL', `cleanup-${name}-discovery`, error); + } + for (const id of Array.from(ids)) { + try { + await poll( + async () => { + try { + await resource.destroy({ + identifier: config.grantId, + [idKey]: id, + }); + } catch (error) { + if (![404, 410].includes(statusCode(error))) throw error; + } + return true; + }, + Boolean, + 3 + ); + ids.delete(id); + } catch (error) { + report('FAIL', `cleanup-${name}`, error); + } + } + if (round < 2 && subjects.size) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + } + } + try { + await poll( + async () => { + const remaining = new Set(); + await discover(resource, subjects, remaining); + return !remaining.size && !ids.size; + }, + Boolean, + 5 + ); + report('PASS', `cleanup-${name}-confirmed`); + } catch (error) { + report('FAIL', `cleanup-${name}-confirmed`, error); + } + } + }; + + try { + for (const [index, kind] of ['buffer', 'base64', 'stream'].entries()) { + const subject = `nylas-node-e2e-${randomUUID()}`; + const filename = `sdk-e2e-${index}.bin`; + const bytes = Buffer.alloc(Math.ceil(2.4 * 1024 * 1024), 0x60 + index); + const attachment = (form) => ({ + filename, + contentType: mimeType, + content: + form === 'buffer' + ? bytes + : form === 'base64' + ? bytes.toString('base64') + : Readable.from([bytes]), + }); + draftSubjects.add(subject); + const draftId = await step(`draft-${kind}-create-multipart`, async () => { + const result = await client.drafts.create({ + identifier: config.grantId, + requestBody: createBody(subject, attachment(kind)), + }); + const id = opaqueId(result.data?.id); + drafts.add(id); + return id; + }); + const findDraft = () => + client.drafts.find({ identifier: config.grantId, draftId }); + const found = await step(`draft-${kind}-find`, () => + poll(findDraft, (result) => result.data?.subject === subject) + ); + await validateDownload( + client, + config, + found.data, + bytes, + filename, + `draft-${kind}` + ); + await step(`draft-${kind}-any-email-filter`, () => + poll( + () => + client.drafts.list({ + identifier: config.grantId, + queryParams: { + subject, + anyEmail: [ + config.recipient, + `absent-${randomUUID()}@example.invalid`, + ], + limit: 20, + }, + }), + (result) => + result.data?.some( + (item) => item.id === draftId && item.subject === subject + ) + ) + ); + const updatedSubject = `${subject}-updated`; + draftSubjects.add(updatedSubject); + await step(`draft-${kind}-update-multipart`, async () => { + const result = await client.drafts.update({ + identifier: config.grantId, + draftId, + requestBody: { + subject: updatedSubject, + attachments: [attachment(['base64', 'stream', 'buffer'][index])], + }, + }); + drafts.add(opaqueId(result.data?.id)); + }); + const updated = await step(`draft-${kind}-find-updated`, () => + poll(findDraft, (result) => result.data?.subject === updatedSubject) + ); + await validateDownload( + client, + config, + updated.data, + bytes, + filename, + `draft-${kind}-updated` + ); + await step(`draft-${kind}-delete`, () => + client.drafts.destroy({ identifier: config.grantId, draftId }) + ); + await step(`draft-${kind}-delete-visible`, () => + poll(async () => { + try { + await findDraft(); + return false; + } catch (error) { + if ([404, 410].includes(statusCode(error))) return true; + throw error; + } + }, Boolean) + ); + drafts.delete(draftId); + draftSubjects.delete(subject); + draftSubjects.delete(updatedSubject); + } + + if (grant.provider !== 'microsoft') { + report('SKIP', 'upload-reference-provider-unavailable'); + } else { + const subject = `nylas-node-e2e-${randomUUID()}`; + const filename = 'sdk-upload-session-e2e.bin'; + const bytes = Buffer.alloc(1024 * 1024, 0x75); + const session = await step('upload-session-create', async () => { + const result = await client.attachments.createUploadSession({ + identifier: config.grantId, + requestBody: { filename, contentType: mimeType, size: bytes.length }, + }); + validateUploadSession(result.data, config, bytes, filename); + return result.data; + }); + await step('upload-presigned-put-without-auth', async () => { + const { url, headers } = validateUploadSession( + session, + config, + bytes, + filename + ); + const response = await fetch(url, { + method: 'PUT', + headers, + body: bytes, + redirect: 'error', + signal: AbortSignal.timeout(30000), + }); + if (!response.ok) { + const error = new Error('Upload failed.'); + error.statusCode = response.status; + await response.body?.cancel(); + throw error; + } + await response.body?.cancel(); + }); + await step('upload-session-complete', async () => { + const result = await client.attachments.completeUploadSession({ + identifier: config.grantId, + attachmentId: session.attachmentId, + }); + check( + result.data?.attachmentId === session.attachmentId && + result.data.grantId === config.grantId && + result.data.status === 'ready' + ); + }); + messageSubjects.add(subject); + const messageId = await step( + 'upload-reference-send-once-to-self', + async () => { + // A send failure is never retried: its outcome may be ambiguous. + const result = await client.messages.send({ + identifier: config.grantId, + requestBody: createBody(subject, { id: session.attachmentId }), + }); + const id = opaqueId(result.data?.id); + messages.add(id); + return id; + } + ); + const sent = await step('upload-reference-message-visible', () => + poll( + () => client.messages.find({ identifier: config.grantId, messageId }), + (result) => + result.data?.subject === subject && + result.data.attachments?.some( + (item) => item.filename === filename && item.id + ) + ) + ); + await validateDownload( + client, + config, + sent.data, + bytes, + filename, + 'upload-reference-message' + ); + await step('self-message-list-visible', () => + poll( + async () => { + const result = await client.messages.list({ + identifier: config.grantId, + queryParams: { subject, anyEmail: [config.recipient], limit: 20 }, + }); + for (const item of result.data || []) { + if ( + item.subject === subject && + selfRecipient(item, config.recipient) + ) { + messages.add(opaqueId(item.id)); + } + } + return result; + }, + (result) => + result.data?.some( + (item) => + item.subject === subject && + item.from?.some( + (sender) => + sender.email?.toLowerCase() === + config.recipient.toLowerCase() + ) + ) + ) + ); + } + report('SKIP', 'transactional-domain-not-configured'); + } finally { + await cleanup(); + } +} + +async function main() { + const args = process.argv.slice(2); + const envPosition = args.indexOf('--test-account-file'); + const verifyOnly = args.includes('--verify-only'); + check( + envPosition >= 0 && + typeof args[envPosition + 1] === 'string' && + (verifyOnly || args.includes('--allow-test-account-writes')) && + typeof parseEnv === 'function' + ); + const config = configFromFile(path.resolve(args[envPosition + 1])); + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nylas-live-e2e-')); + try { + const Nylas = await step('fresh-packed-artifact-installed', () => + buildInstalledPackage(tempDir) + ); + await runProviderChecks(Nylas, config, verifyOnly); + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } +} + +if (require.main === module) { + main() + .catch((error) => report('FAIL', currentCase, error)) + .finally(() => { + if (failed) process.exitCode = 1; + }); +} + +module.exports = { configFromFile, validateUploadSession }; diff --git a/tests/e2e/LIVE.md b/tests/e2e/LIVE.md new file mode 100644 index 00000000..881b5a62 --- /dev/null +++ b/tests/e2e/LIVE.md @@ -0,0 +1,47 @@ +This optional runner performs real writes in one configured test mailbox. It is +separate from `npm run test:e2e` and is never invoked by CI. Use Node.js 24 and +install the repository's development dependencies first. + +Validate the updated account configuration without creating objects: + +```sh +node scripts/testLiveE2E.js --test-account-file /absolute/path/to/examples/.env --verify-only +``` + +After that check succeeds, explicitly enable test-account writes: + +```sh +node scripts/testLiveE2E.js --test-account-file /absolute/path/to/examples/.env --allow-test-account-writes +``` + +The runner reads `NYLAS_API_KEY`, `NYLAS_API_URI`, `NYLAS_GRANT_ID`, and +`TEST_EMAIL` as data from the selected file. It accepts the US/EU Nylas API origins +and requires the current grant to be valid and its email address to match +`TEST_EMAIL`. Credentials are not forwarded to build/install subprocesses. +Output contains case names and status codes only; raw errors and account data +are suppressed. + +Each invocation freshly builds, packs, and installs the SDK. It creates three +uniquely named drafts with Buffer, base64, and unknown-size stream attachments +whose encoded content exceeds 3 MiB, then finds, filters, updates, downloads, and +deletes them. Download checks run when the provider exposes attachment IDs. + +For a Microsoft grant, it also creates an upload session, validates the response, +uploads 1 MiB of synthetic bytes directly to the documented HTTPS storage host +without an authorization header, completes the session, and sends its reference +once to the same test mailbox. It reads and downloads the resulting attachment. +Send requests are never retried automatically. A different provider reports this +case as unavailable. No transactional send is attempted without a configured +domain. + +A `finally` block deletes returned object IDs and revisits exact synthetic +subjects to catch late self-delivery or uncertain write outcomes. Consistency +polling and cleanup attempts are bounded. Any failed cleanup fails the run. +Upload sessions have no SDK delete endpoint and expire through the API's normal +retention policy. + +The upload checks follow the current +[create-session contract](https://developer.nylas.com/docs/reference/api/attachments/create-attachment-upload-session/), +[completion contract](https://developer.nylas.com/docs/reference/api/attachments/complete-attachment-upload-session/), +and [large-attachment guide](https://developer.nylas.com/docs/v3/email/send-large-attachments/). +Unexpected response fields, upload hosts, methods, or headers fail closed. diff --git a/tests/e2e/live-runner-safety.test.cjs b/tests/e2e/live-runner-safety.test.cjs new file mode 100644 index 00000000..3bff3a3f --- /dev/null +++ b/tests/e2e/live-runner-safety.test.cjs @@ -0,0 +1,134 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { spawnSync } = require('node:child_process'); +const { test } = require('node:test'); +const { parseEnv } = require('node:util'); +const { + configFromFile, + validateUploadSession, +} = require('../../scripts/testLiveE2E.js'); + +const grantId = '11111111-1111-4111-8111-111111111111'; +const bytes = Buffer.alloc(100); +function session() { + return { + attachmentId: '22222222-2222-4222-8222-222222222222', + method: 'PUT', + grantId, + filename: 'fixture.bin', + contentType: 'application/octet-stream', + size: bytes.length, + maxSize: 157286400, + expiresAt: new Date(Date.now() + 30 * 60 * 1000).toISOString(), + url: 'https://storage.googleapis.com/upload/storage/v1/b/fixture/o?uploadType=resumable&upload_id=fixture-upload-id', + headers: { 'Content-Type': 'application/octet-stream' }, + }; +} + +test('live runner refuses missing opt-in before opening any environment file', () => { + const result = spawnSync( + process.execPath, + [ + path.join(__dirname, '../../scripts/testLiveE2E.js'), + '--test-account-file', + '/does/not/exist', + ], + { encoding: 'utf8' } + ); + assert.equal(result.status, 1); + assert.equal(result.stdout, 'FAIL configuration\n'); + assert.equal(result.stderr, ''); +}); + +test( + 'environment parsing treats values as data and rejects an unknown API origin', + { skip: typeof parseEnv !== 'function' }, + (t) => { + const directory = fs.mkdtempSync( + path.join(os.tmpdir(), 'nylas-live-config-test-') + ); + t.after(() => fs.rmSync(directory, { recursive: true, force: true })); + const filename = path.join(directory, 'fixture.env'); + const write = (origin) => + fs.writeFileSync( + filename, + [ + 'NYLAS_API_KEY="fixture-key-$(do-not-execute)"', + `NYLAS_GRANT_ID=${grantId}`, + 'TEST_EMAIL=fixture@example.invalid', + `NYLAS_API_URI=${origin}`, + ].join('\n') + ); + write('https://api.us.nylas.com'); + assert.equal( + configFromFile(filename).apiKey, + 'fixture-key-$(do-not-execute)' + ); + write('http://127.0.0.1:9999'); + assert.throws(() => configFromFile(filename)); + } +); + +test('presigned upload accepts the documented storage response without authorization', () => { + const result = validateUploadSession( + session(), + { grantId }, + bytes, + 'fixture.bin' + ); + assert.equal(result.url.hostname, 'storage.googleapis.com'); + assert.equal(result.headers.has('authorization'), false); + assert.equal(result.headers.get('content-type'), 'application/octet-stream'); +}); + +for (const [name, change] of [ + [ + 'unexpected-host', + (value) => { + value.url = value.url.replace( + 'storage.googleapis.com', + 'example.invalid' + ); + }, + ], + [ + 'authorization-header', + (value) => { + value.headers.Authorization = 'fixture-only'; + }, + ], + [ + 'redirect-method', + (value) => { + value.method = 'POST'; + }, + ], + [ + 'wrong-grant', + (value) => { + value.grantId = 'different'; + }, + ], + [ + 'wrong-size', + (value) => { + value.size++; + }, + ], + [ + 'expired-session', + (value) => { + value.expiresAt = new Date(0).toISOString(); + }, + ], +]) { + test(`presigned upload rejects ${name}`, () => { + const value = session(); + change(value); + assert.throws(() => + validateUploadSession(value, { grantId }, bytes, 'fixture.bin') + ); + }); +} From 7610bbe95b3eb9a1c1932fa0dd4de6e19dc3af1e Mon Sep 17 00:00:00 2001 From: Aaron de Mello Date: Wed, 4 Nov 2026 15:26:07 -0500 Subject: [PATCH 4/6] test: cover live multipart sends to the same test mailbox --- scripts/testLiveE2E.js | 76 ++++++++++++++++++++++++++++++++++++++++++ tests/e2e/LIVE.md | 8 +++-- 2 files changed, 82 insertions(+), 2 deletions(-) diff --git a/scripts/testLiveE2E.js b/scripts/testLiveE2E.js index 9d00987b..ab0b7139 100644 --- a/scripts/testLiveE2E.js +++ b/scripts/testLiveE2E.js @@ -432,6 +432,82 @@ async function runProviderChecks(Nylas, config, verifyOnly) { draftSubjects.delete(updatedSubject); } + for (const [index, kind] of ['buffer', 'base64', 'stream'].entries()) { + const subject = `nylas-node-e2e-${randomUUID()}`; + const filename = `sdk-send-e2e-${index}.bin`; + const bytes = Buffer.alloc(Math.ceil(2.4 * 1024 * 1024), 0x70 + index); + const content = + kind === 'buffer' + ? bytes + : kind === 'base64' + ? bytes.toString('base64') + : Readable.from([bytes]); + messageSubjects.add(subject); + const messageId = await step( + `message-${kind}-send-once-to-self`, + async () => { + // Never retry a send POST, even when its outcome is ambiguous. + const result = await client.messages.send({ + identifier: config.grantId, + requestBody: createBody(subject, { + filename, + contentType: mimeType, + content, + }), + }); + const id = opaqueId(result.data?.id); + messages.add(id); + return id; + } + ); + const sent = await step(`message-${kind}-attachment-visible`, () => + poll( + () => client.messages.find({ identifier: config.grantId, messageId }), + (result) => + result.data?.subject === subject && + selfRecipient(result.data, config.recipient) && + result.data.attachments?.some( + (item) => item.filename === filename && item.id + ), + 12 + ) + ); + await validateDownload( + client, + config, + sent.data, + bytes, + filename, + `message-${kind}` + ); + await step(`message-${kind}-self-filter-visible`, () => + poll( + async () => { + const result = await client.messages.list({ + identifier: config.grantId, + queryParams: { subject, anyEmail: [config.recipient], limit: 20 }, + }); + for (const item of result.data || []) { + if ( + item.subject === subject && + selfRecipient(item, config.recipient) + ) { + messages.add(opaqueId(item.id)); + } + } + return result; + }, + (result) => + result.data?.some( + (item) => + item.subject === subject && + selfRecipient(item, config.recipient) + ), + 12 + ) + ); + } + if (grant.provider !== 'microsoft') { report('SKIP', 'upload-reference-provider-unavailable'); } else { diff --git a/tests/e2e/LIVE.md b/tests/e2e/LIVE.md index 881b5a62..26f0cd20 100644 --- a/tests/e2e/LIVE.md +++ b/tests/e2e/LIVE.md @@ -26,7 +26,11 @@ uniquely named drafts with Buffer, base64, and unknown-size stream attachments whose encoded content exceeds 3 MiB, then finds, filters, updates, downloads, and deletes them. Download checks run when the provider exposes attachment IDs. -For a Microsoft grant, it also creates an upload session, validates the response, +It also sends one Buffer, base64, and unknown-size stream attachment message to +the same mailbox, reads each resulting message, and verifies its downloaded +attachment bytes. These use the same >3 MiB encoded payloads as the draft cases. + +For a Microsoft grant, it additionally creates an upload session, validates the response, uploads 1 MiB of synthetic bytes directly to the documented HTTPS storage host without an authorization header, completes the session, and sends its reference once to the same test mailbox. It reads and downloads the resulting attachment. @@ -44,4 +48,4 @@ The upload checks follow the current [create-session contract](https://developer.nylas.com/docs/reference/api/attachments/create-attachment-upload-session/), [completion contract](https://developer.nylas.com/docs/reference/api/attachments/complete-attachment-upload-session/), and [large-attachment guide](https://developer.nylas.com/docs/v3/email/send-large-attachments/). -Unexpected response fields, upload hosts, methods, or headers fail closed. +Unexpected upload hosts, methods, headers, or required field values fail closed. From ccb2b71974f08b626de7dd7c280d3535c1882be2 Mon Sep 17 00:00:00 2001 From: Aaron de Mello Date: Wed, 4 Nov 2026 15:34:06 -0500 Subject: [PATCH 5/6] test: verify soft-delete cleanup and retain private recovery state --- scripts/testLiveE2E.js | 172 +++++++++++++++++++++++--- tests/e2e/LIVE.md | 18 ++- tests/e2e/live-cleanup.test.cjs | 85 +++++++++++++ tests/e2e/live-runner-safety.test.cjs | 25 ++++ 4 files changed, 280 insertions(+), 20 deletions(-) create mode 100644 tests/e2e/live-cleanup.test.cjs diff --git a/scripts/testLiveE2E.js b/scripts/testLiveE2E.js index ab0b7139..3b4ac04d 100644 --- a/scripts/testLiveE2E.js +++ b/scripts/testLiveE2E.js @@ -231,6 +231,99 @@ function validateUploadSession(session, config, bytes, filename) { return { url, headers }; } +function isMessageInTrash(message, trashFolderIds) { + return ( + Array.isArray(message?.folders) && + message.folders.some((folder) => trashFolderIds.has(folder)) + ); +} + +async function cleanupOwnedObject(resource, options) { + const { + identifier, + id, + idKey, + subjects, + recipient, + isMessage, + trashFolderIds, + } = options; + const params = { identifier, [idKey]: id }; + const read = async () => { + try { + const result = await resource.find(params); + check( + subjects.has(result.data?.subject) && + selfRecipient(result.data, recipient) + ); + return result.data; + } catch (error) { + if ([404, 410].includes(statusCode(error))) return undefined; + throw error; + } + }; + const existing = await read(); + if (!existing || (isMessage && isMessageInTrash(existing, trashFolderIds))) + return; + // The documented default is a soft delete. Never request hard_delete or + // repeatedly delete a still-visible trashed message to force a 404. + try { + await resource.destroy(params); + } catch (error) { + if (![404, 410].includes(statusCode(error))) throw error; + } + await poll( + async () => { + const current = await read(); + return ( + !current || (isMessage && isMessageInTrash(current, trashFolderIds)) + ); + }, + Boolean, + 5 + ); +} + +function createCleanupManifest() { + const directory = fs.mkdtempSync( + path.join(os.tmpdir(), 'nylas-live-e2e-state-') + ); + fs.chmodSync(directory, 0o700); + const filename = path.join(directory, 'manifest.json'); + return { + write(state) { + const serialized = JSON.stringify(state); + check(serialized.length <= 65536); + const temporary = path.join(directory, 'manifest.next'); + fs.writeFileSync(temporary, serialized, { mode: 0o600 }); + fs.renameSync(temporary, filename); + }, + remove() { + fs.rmSync(directory, { recursive: true, force: true }); + }, + filename, + }; +} + +async function findTrashFolderIds(client, config, provider) { + // Google system label IDs are stable; other providers expose the common + // \Trash folder attribute through the Folders API. + if (provider === 'google') return new Set(['TRASH']); + const ids = new Set(); + let pageCount = 0; + for await (const page of client.folders.list({ + identifier: config.grantId, + queryParams: { limit: 100 }, + })) { + check(++pageCount <= 3 && Array.isArray(page.data)); + for (const folder of page.data) { + if (folder.attributes?.includes('\\Trash')) ids.add(opaqueId(folder.id)); + } + } + check(ids.size > 0); + return ids; +} + async function runProviderChecks(Nylas, config, verifyOnly) { const client = new Nylas({ apiKey: config.apiKey, @@ -254,6 +347,24 @@ async function runProviderChecks(Nylas, config, verifyOnly) { const messages = new Set(); const draftSubjects = new Set(); const messageSubjects = new Set(); + const trashFolderIds = await findTrashFolderIds( + client, + config, + grant.provider + ); + const manifest = createCleanupManifest(); + const createdAt = Date.now(); + const syncState = () => + manifest.write({ + version: 1, + createdAt, + drafts: Array.from(drafts), + messages: Array.from(messages), + draftSubjects: Array.from(draftSubjects), + messageSubjects: Array.from(messageSubjects), + }); + syncState(); + let cleanupConfirmed = true; const createBody = (subject, attachment) => ({ to: [{ email: config.recipient }], subject, @@ -268,8 +379,14 @@ async function runProviderChecks(Nylas, config, verifyOnly) { }); check(Array.isArray(result.data) && !result.nextCursor); for (const item of result.data) { - if (item.subject === subject && selfRecipient(item, config.recipient)) { + if ( + item.subject === subject && + selfRecipient(item, config.recipient) && + (resource !== client.messages || + !isMessageInTrash(item, trashFolderIds)) + ) { ids.add(opaqueId(item.id)); + syncState(); } } } @@ -280,33 +397,33 @@ async function runProviderChecks(Nylas, config, verifyOnly) { ['message', client.messages, messages, messageSubjects, 'messageId'], ]) { if (!ids.size && !subjects.size) continue; + const attempted = new Set(); // Revisit exact synthetic subjects to catch a late self-delivery or an // ambiguous POST outcome. No unrelated message is eligible for deletion. for (let round = 0; round < 3; round++) { try { await discover(resource, subjects, ids); } catch (error) { + cleanupConfirmed = false; report('FAIL', `cleanup-${name}-discovery`, error); } for (const id of Array.from(ids)) { + if (attempted.has(id)) continue; + attempted.add(id); try { - await poll( - async () => { - try { - await resource.destroy({ - identifier: config.grantId, - [idKey]: id, - }); - } catch (error) { - if (![404, 410].includes(statusCode(error))) throw error; - } - return true; - }, - Boolean, - 3 - ); + await cleanupOwnedObject(resource, { + identifier: config.grantId, + id, + idKey, + subjects, + recipient: config.recipient, + isMessage: name === 'message', + trashFolderIds, + }); ids.delete(id); + syncState(); } catch (error) { + cleanupConfirmed = false; report('FAIL', `cleanup-${name}`, error); } } @@ -326,6 +443,7 @@ async function runProviderChecks(Nylas, config, verifyOnly) { ); report('PASS', `cleanup-${name}-confirmed`); } catch (error) { + cleanupConfirmed = false; report('FAIL', `cleanup-${name}-confirmed`, error); } } @@ -347,6 +465,7 @@ async function runProviderChecks(Nylas, config, verifyOnly) { : Readable.from([bytes]), }); draftSubjects.add(subject); + syncState(); const draftId = await step(`draft-${kind}-create-multipart`, async () => { const result = await client.drafts.create({ identifier: config.grantId, @@ -354,6 +473,7 @@ async function runProviderChecks(Nylas, config, verifyOnly) { }); const id = opaqueId(result.data?.id); drafts.add(id); + syncState(); return id; }); const findDraft = () => @@ -391,6 +511,7 @@ async function runProviderChecks(Nylas, config, verifyOnly) { ); const updatedSubject = `${subject}-updated`; draftSubjects.add(updatedSubject); + syncState(); await step(`draft-${kind}-update-multipart`, async () => { const result = await client.drafts.update({ identifier: config.grantId, @@ -401,6 +522,7 @@ async function runProviderChecks(Nylas, config, verifyOnly) { }, }); drafts.add(opaqueId(result.data?.id)); + syncState(); }); const updated = await step(`draft-${kind}-find-updated`, () => poll(findDraft, (result) => result.data?.subject === updatedSubject) @@ -430,6 +552,7 @@ async function runProviderChecks(Nylas, config, verifyOnly) { drafts.delete(draftId); draftSubjects.delete(subject); draftSubjects.delete(updatedSubject); + syncState(); } for (const [index, kind] of ['buffer', 'base64', 'stream'].entries()) { @@ -443,6 +566,7 @@ async function runProviderChecks(Nylas, config, verifyOnly) { ? bytes.toString('base64') : Readable.from([bytes]); messageSubjects.add(subject); + syncState(); const messageId = await step( `message-${kind}-send-once-to-self`, async () => { @@ -457,6 +581,7 @@ async function runProviderChecks(Nylas, config, verifyOnly) { }); const id = opaqueId(result.data?.id); messages.add(id); + syncState(); return id; } ); @@ -493,6 +618,7 @@ async function runProviderChecks(Nylas, config, verifyOnly) { selfRecipient(item, config.recipient) ) { messages.add(opaqueId(item.id)); + syncState(); } } return result; @@ -556,6 +682,7 @@ async function runProviderChecks(Nylas, config, verifyOnly) { ); }); messageSubjects.add(subject); + syncState(); const messageId = await step( 'upload-reference-send-once-to-self', async () => { @@ -566,6 +693,7 @@ async function runProviderChecks(Nylas, config, verifyOnly) { }); const id = opaqueId(result.data?.id); messages.add(id); + syncState(); return id; } ); @@ -600,6 +728,7 @@ async function runProviderChecks(Nylas, config, verifyOnly) { selfRecipient(item, config.recipient) ) { messages.add(opaqueId(item.id)); + syncState(); } } return result; @@ -620,6 +749,9 @@ async function runProviderChecks(Nylas, config, verifyOnly) { report('SKIP', 'transactional-domain-not-configured'); } finally { await cleanup(); + syncState(); + if (cleanupConfirmed) manifest.remove(); + else report('FAIL', 'cleanup-private-manifest-retained'); } } @@ -653,4 +785,10 @@ if (require.main === module) { }); } -module.exports = { configFromFile, validateUploadSession }; +module.exports = { + configFromFile, + validateUploadSession, + isMessageInTrash, + cleanupOwnedObject, + createCleanupManifest, +}; diff --git a/tests/e2e/LIVE.md b/tests/e2e/LIVE.md index 26f0cd20..c22231c0 100644 --- a/tests/e2e/LIVE.md +++ b/tests/e2e/LIVE.md @@ -38,9 +38,21 @@ Send requests are never retried automatically. A different provider reports this case as unavailable. No transactional send is attempted without a configured domain. -A `finally` block deletes returned object IDs and revisits exact synthetic -subjects to catch late self-delivery or uncertain write outcomes. Consistency -polling and cleanup attempts are bounded. Any failed cleanup fails the run. +A `finally` block cleans up returned object IDs and revisits exact synthetic +subjects to catch late self-delivery or uncertain write outcomes. Draft deletion +must become visible as absence. Message cleanup accepts the API's documented +soft-delete state: membership in the provider's Trash folder, even when the +message remains readable and retains a Sent label. It never requests irreversible +`hard_delete` or changes account settings. See the +[Delete Message contract](https://developer.nylas.com/docs/reference/api/messages/delete-message/). + +Consistency polling is bounded, and failed cleanup fails the run. Before writes, +the runner creates a private `nylas-live-e2e-state-*` directory in the OS temporary +directory. Its mode-0600 `manifest.json` tracks only synthetic subjects, creation +time, and owned object IDs. It contains no credentials, email addresses, grant +IDs, bodies, or upload URLs. Updates are atomic. The manifest is removed after +confirmed cleanup and retained after failure for targeted recovery; do not rerun +the full suite to recover an earlier run, because that would create more objects. Upload sessions have no SDK delete endpoint and expire through the API's normal retention policy. diff --git a/tests/e2e/live-cleanup.test.cjs b/tests/e2e/live-cleanup.test.cjs new file mode 100644 index 00000000..5516cfd8 --- /dev/null +++ b/tests/e2e/live-cleanup.test.cjs @@ -0,0 +1,85 @@ +const assert = require('node:assert/strict'); +const http = require('node:http'); +const path = require('node:path'); +const { createRequire } = require('node:module'); +const { test } = require('node:test'); +const { cleanupOwnedObject } = require('../../scripts/testLiveE2E.js'); + +const consumerDir = process.env.NYLAS_E2E_CONSUMER_DIR; +assert(consumerDir, 'Run this suite with npm run test:e2e'); +const Nylas = createRequire(path.join(consumerDir, 'package.json'))('nylas'); +const subject = 'nylas-node-e2e-11111111-1111-4111-8111-111111111111'; +const recipient = 'fixture@example.invalid'; + +async function fixture(t, objectSubject = subject) { + const requests = []; + const message = { + id: 'fixture-message', + subject: objectSubject, + to: [{ email: recipient }], + folders: ['INBOX', 'SENT'], + }; + const server = http.createServer((request, response) => { + requests.push({ method: request.method, url: request.url }); + response.setHeader('content-type', 'application/json'); + if (request.method === 'DELETE') { + message.folders = ['TRASH', 'SENT']; + response.end(JSON.stringify({ request_id: 'fixture-delete' })); + } else { + response.end( + JSON.stringify({ request_id: 'fixture-read', data: message }) + ); + } + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + t.after(() => { + server.closeAllConnections(); + return new Promise((resolve) => server.close(resolve)); + }); + const client = new Nylas({ + apiKey: 'fixture-key', + apiUri: `http://127.0.0.1:${server.address().port}`, + timeout: 5, + }); + return { + client, + requests, + message, + options: { + identifier: 'fixture-grant', + id: 'fixture-message', + idKey: 'messageId', + subjects: new Set([subject]), + recipient, + isMessage: true, + trashFolderIds: new Set(['TRASH']), + }, + }; +} + +test('live cleanup accepts a still-readable soft-deleted message without repeated deletion', async (t) => { + const { client, requests, options } = await fixture(t); + await cleanupOwnedObject(client.messages, options); + const visible = await client.messages.find({ + identifier: options.identifier, + messageId: options.id, + }); + assert.deepEqual(visible.data.folders, ['TRASH', 'SENT']); + await cleanupOwnedObject(client.messages, options); + const deletes = requests.filter((request) => request.method === 'DELETE'); + assert.equal(deletes.length, 1); + assert.equal( + deletes[0].url, + '/v3/grants/fixture-grant/messages/fixture-message' + ); + assert(requests.every((request) => !request.url.includes('hard_delete'))); +}); + +test('live cleanup refuses an object outside its exact synthetic subject set', async (t) => { + const { client, requests, options } = await fixture(t, 'unrelated-fixture'); + await assert.rejects(cleanupOwnedObject(client.messages, options)); + assert.equal( + requests.filter((request) => request.method === 'DELETE').length, + 0 + ); +}); diff --git a/tests/e2e/live-runner-safety.test.cjs b/tests/e2e/live-runner-safety.test.cjs index 3bff3a3f..48113198 100644 --- a/tests/e2e/live-runner-safety.test.cjs +++ b/tests/e2e/live-runner-safety.test.cjs @@ -8,6 +8,7 @@ const { parseEnv } = require('node:util'); const { configFromFile, validateUploadSession, + createCleanupManifest, } = require('../../scripts/testLiveE2E.js'); const grantId = '11111111-1111-4111-8111-111111111111'; @@ -132,3 +133,27 @@ for (const [name, change] of [ ); }); } + +test('cleanup manifest is private and preserves bounded synthetic recovery state', (t) => { + const manifest = createCleanupManifest(); + t.after(() => manifest.remove()); + const state = { + version: 1, + createdAt: 1, + drafts: [], + messages: ['fixture-owned-id'], + draftSubjects: [], + messageSubjects: ['nylas-node-e2e-fixture'], + }; + manifest.write(state); + assert.deepEqual( + JSON.parse(fs.readFileSync(manifest.filename, 'utf8')), + state + ); + assert.equal(fs.statSync(manifest.filename).mode & 0o777, 0o600); + assert.equal( + fs.statSync(path.dirname(manifest.filename)).mode & 0o777, + 0o700 + ); + assert.throws(() => manifest.write({ oversized: 'x'.repeat(65537) })); +}); From 57e64915bd71509b73927a639bde5a14e8a7db83 Mon Sep 17 00:00:00 2001 From: Aaron de Mello Date: Wed, 4 Nov 2026 15:43:48 -0500 Subject: [PATCH 6/6] NYL-476 require intact upload headers in packed SDK E2E --- tests/e2e/resources.test.cjs | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/tests/e2e/resources.test.cjs b/tests/e2e/resources.test.cjs index 6e0896f8..fbbe590f 100644 --- a/tests/e2e/resources.test.cjs +++ b/tests/e2e/resources.test.cjs @@ -31,7 +31,10 @@ async function withServer(run) { attachment_id: UPLOADED_ID, method: 'PUT', url: `http://${req.headers.host}/upload`, - headers: { 'Content-Type': 'application/octet-stream' }, + headers: { + 'Content-Type': 'application/octet-stream', + 'x-goog-upload-protocol': 'resumable', + }, expires_at: '2099-01-01T00:00:00Z', max_size: 157286400, size: 10, @@ -43,7 +46,22 @@ async function withServer(run) { data = { attachment_id: UPLOADED_ID, grant_id: 'grant', status: 'ready' }; } - res.writeHead(200, { 'Content-Type': 'application/json' }); + if ( + req.method === 'PUT' && + req.url === '/upload' && + (req.headers['content-type'] !== 'application/octet-stream' || + req.headers['x-goog-upload-protocol'] !== 'resumable') + ) { + res.writeHead(400, { 'Content-Type': 'application/json' }); + res.end( + JSON.stringify({ error: 'Required upload headers are missing.' }) + ); + return; + } + res.writeHead(200, { + 'Content-Type': 'application/json', + 'X-Fixture-Response': 'upload-session', + }); res.end(JSON.stringify({ request_id: 'fixture-request', data })); }); await new Promise((resolve, reject) => { @@ -352,6 +370,14 @@ test('public upload-session flow can send its completed ID without SDK or fetch body: bytes, }); assert.equal(uploaded.status, 200); + assert.deepEqual(created.data.headers, { + 'Content-Type': 'application/octet-stream', + 'x-goog-upload-protocol': 'resumable', + }); + assert.equal(created.headers.contentType, 'application/json'); + assert.equal(created.headers.xFixtureResponse, 'upload-session'); + assert.equal(created.rawHeaders['content-type'], 'application/json'); + assert.equal(created.rawHeaders['x-fixture-response'], 'upload-session'); const completed = await client.attachments.completeUploadSession({ identifier: 'grant', attachmentId: created.data.attachmentId, @@ -375,6 +401,11 @@ test('public upload-session flow can send its completed ID without SDK or fetch ] ); assert.deepEqual(requests[1].body, bytes); + assert.equal( + requests[1].headers['content-type'], + 'application/octet-stream' + ); + assert.equal(requests[1].headers['x-goog-upload-protocol'], 'resumable'); assert.equal(requests[1].headers.authorization, undefined); assert.deepEqual(JSON.parse(requests[3].body).attachments, [ { id: UPLOADED_ID },