Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add secureDeliveryProxyUrlResolver and secureUploadsTokenResolver options #659

Merged
merged 6 commits into from
May 24, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 20 additions & 8 deletions abstract/Block.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { LocaleManager, localeStateKey } from './LocaleManager.js';
import { l10nProcessor } from './l10nProcessor.js';
import { sharedConfigKey } from './sharedConfigKey.js';
import { initialConfig } from '../blocks/Config/initialConfig.js';
import { extractFilename, extractOperations, extractUuid } from '../utils/cdn-utils.js';

const TAG_PREFIX = 'lr-';

Expand Down Expand Up @@ -242,15 +243,26 @@ export class Block extends BaseComponent {
* @returns {String}
*/
proxyUrl(url) {
let previewProxy = this.cfg.secureDeliveryProxy;
if (!previewProxy) {
return url;
if (this.cfg.secureDeliveryProxy && this.cfg.secureDeliveryProxyUrlResolver) {
console.warn(
'Both secureDeliveryProxy and secureDeliveryProxyUrlResolver are set. Using secureDeliveryProxyUrlResolver.',
);
nd0ut marked this conversation as resolved.
Show resolved Hide resolved
}
return applyTemplateData(
previewProxy,
{ previewUrl: url },
{ transform: (value) => window.encodeURIComponent(value) },
);
if (this.cfg.secureDeliveryProxyUrlResolver) {
return this.cfg.secureDeliveryProxyUrlResolver(url, {
uuid: extractUuid(url),
cdnUrlModifiers: extractOperations(url),
fileName: extractFilename(url),
});
}
if (this.cfg.secureDeliveryProxy) {
return applyTemplateData(
this.cfg.secureDeliveryProxy,
{ previewUrl: url },
{ transform: (value) => window.encodeURIComponent(value) },
);
}
return url;
}

/** @returns {import('../types').ConfigType} } */
Expand Down
2 changes: 2 additions & 0 deletions abstract/CTX.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,6 @@ export const uploaderBlockCtx = (fnCtx) => ({
'*groupInfo': null,
/** @type {Set<string>} */
'*uploadTrigger': new Set(),
/** @type {import('./SecureUploadsManager.js').SecureUploadsManager | null} */
'*secureUploadsManager': null,
});
63 changes: 63 additions & 0 deletions abstract/SecureUploadsManager.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// @ts-check

/** @param {import('../types').SecureUploadsSignatureAndExpire} secureToken */
const isSecureTokenExpired = (secureToken) => {
const { secureExpire } = secureToken;
return Date.now() > Number(secureExpire);
};

export class SecureUploadsManager {
/**
* @private
* @type {import('./UploaderBlock.js').UploaderBlock}
*/
_block;
/**
* @private
* @type {import('../types').SecureUploadsSignatureAndExpire | null}
*/
_secureToken = null;

/** @param {import('./UploaderBlock.js').UploaderBlock} block */
constructor(block) {
this._block = block;
}

/** @returns {Promise<import('../types').SecureUploadsSignatureAndExpire | null>} */
async getSecureToken() {
const { secureSignature, secureExpire, secureUploadsSignatureResolver } = this._block.cfg;

if ((secureSignature || secureExpire) && secureUploadsSignatureResolver) {
console.warn(
'Both secureSignature/secureExpire and secureUploadsSignatureResolver are set. secureUploadsSignatureResolver will be used.',
);
}

if (secureUploadsSignatureResolver) {
this._block.debugPrint('Secure signature resolver is set. Fetching secure token...');

if (!this._secureToken || isSecureTokenExpired(this._secureToken)) {
const result = await secureUploadsSignatureResolver();
this._block.debugPrint('Secure token fetched:', result);

this._secureToken = result ?? null;
}

return this._secureToken;
}

if (secureSignature && secureExpire) {
this._block.debugPrint('Secure signature and expire are set. Using them...', {
secureSignature,
secureExpire,
});

return {
secureSignature,
secureExpire,
};
}

return null;
}
}
19 changes: 14 additions & 5 deletions abstract/UploaderBlock.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { TypedCollection } from './TypedCollection.js';
import { buildOutputCollectionState } from './buildOutputCollectionState.js';
import { uploadEntrySchema } from './uploadEntrySchema.js';
import { parseCdnUrl } from '../utils/parseCdnUrl.js';
import { SecureUploadsManager } from './SecureUploadsManager.js';
export class UploaderBlock extends ActivityBlock {
couldBeCtxOwner = false;
isCtxOwner = false;
Expand Down Expand Up @@ -184,6 +185,10 @@ export class UploaderBlock extends ActivityBlock {
if (this.__initialUploadMetadata) {
this.$['*uploadMetadata'] = this.__initialUploadMetadata;
}

if (!this.$['*secureUploadsManager']) {
this.$['*secureUploadsManager'] = new SecureUploadsManager(this);
}
}

// TODO: Probably we should not allow user to override `source` property
Expand Down Expand Up @@ -582,7 +587,7 @@ export class UploaderBlock extends ActivityBlock {
* @param {import('../types').OutputCollectionState} collectionState
*/
async _createGroup(collectionState) {
const uploadClientOptions = this.getUploadClientOptions();
const uploadClientOptions = await this.getUploadClientOptions();
const uuidList = collectionState.allEntries.map((entry) => {
return entry.uuid + (entry.cdnUrlModifiers ? `/${entry.cdnUrlModifiers}` : '');
});
Expand Down Expand Up @@ -822,17 +827,21 @@ export class UploaderBlock extends ActivityBlock {
return configValue;
}

/** @returns {import('@uploadcare/upload-client').FileFromOptions} */
getUploadClientOptions() {
/** @returns {Promise<import('@uploadcare/upload-client').FileFromOptions>} */
async getUploadClientOptions() {
/** @type {SecureUploadsManager} */
const secureUploadsManager = this.$['*secureUploadsManager'];
const secureToken = await secureUploadsManager.getSecureToken();

let options = {
store: this.cfg.store,
publicKey: this.cfg.pubkey,
baseCDN: this.cfg.cdnCname,
baseURL: this.cfg.baseUrl,
userAgent: customUserAgent,
integration: this.cfg.userAgentIntegration,
secureSignature: this.cfg.secureSignature,
secureExpire: this.cfg.secureExpire,
secureSignature: secureToken?.secureSignature,
secureExpire: secureToken?.secureExpire,
retryThrottledRequestMaxTimes: this.cfg.retryThrottledRequestMaxTimes,
multipartMinFileSize: this.cfg.multipartMinFileSize,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider adding error handling for secure token retrieval.

- const secureToken = await secureUploadsManager.getSecureToken();
+ let secureToken;
+ try {
+   secureToken = await secureUploadsManager.getSecureToken();
+ } catch (error) {
+   console.error('Failed to retrieve secure token:', error);
+   secureToken = null;
+ }

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
async getUploadClientOptions() {
/** @type {SecureUploadsManager} */
const secureUploadsManager = this.$['*secureUploadsManager'];
const secureToken = await secureUploadsManager.getSecureToken();
let options = {
store: this.cfg.store,
publicKey: this.cfg.pubkey,
baseCDN: this.cfg.cdnCname,
baseURL: this.cfg.baseUrl,
userAgent: customUserAgent,
integration: this.cfg.userAgentIntegration,
secureSignature: this.cfg.secureSignature,
secureExpire: this.cfg.secureExpire,
secureSignature: secureToken?.secureSignature,
secureExpire: secureToken?.secureExpire,
retryThrottledRequestMaxTimes: this.cfg.retryThrottledRequestMaxTimes,
multipartMinFileSize: this.cfg.multipartMinFileSize,
async getUploadClientOptions() {
/** @type {SecureUploadsManager} */
const secureUploadsManager = this.$['*secureUploadsManager'];
let secureToken;
try {
secureToken = await secureUploadsManager.getSecureToken();
} catch (error) {
console.error('Failed to retrieve secure token:', error);
secureToken = null;
}
let options = {
store: this.cfg.store,
publicKey: this.cfg.pubkey,
baseCDN: this.cfg.cdnCname,
baseURL: this.cfg.baseUrl,
userAgent: customUserAgent,
integration: this.cfg.userAgentIntegration,
secureSignature: secureToken?.secureSignature,
secureExpire: secureToken?.secureExpire,
retryThrottledRequestMaxTimes: this.cfg.retryThrottledRequestMaxTimes,
multipartMinFileSize: this.cfg.multipartMinFileSize,

multipartChunkSize: this.cfg.multipartChunkSize,
Expand Down
9 changes: 7 additions & 2 deletions blocks/Config/Config.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,14 @@ const allConfigKeys = /** @type {(keyof import('../../types').ConfigType)[]} */
/**
* Config keys that can't be passed as attribute (because they are object or function)
*
* @type {(keyof import('../../types').ConfigComplexType)[]}
* @type {['metadata', 'localeDefinitionOverride', 'secureUploadsSignatureResolver', 'secureDeliveryProxyUrlResolver']}
*/
const complexConfigKeys = ['metadata', 'localeDefinitionOverride'];
export const complexConfigKeys = [
'metadata',
'localeDefinitionOverride',
'secureUploadsSignatureResolver',
'secureDeliveryProxyUrlResolver',
];

/** @type {(key: keyof import('../../types').ConfigType) => key is keyof import('../../types').ConfigComplexType} */
const isComplexKey = (key) => complexConfigKeys.includes(key);
Expand Down
2 changes: 2 additions & 0 deletions blocks/Config/initialConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,6 @@ export const initialConfig = {
metadata: null,
localeName: 'en',
localeDefinitionOverride: null,
secureUploadsSignatureResolver: null,
secureDeliveryProxyUrlResolver: null,
};
32 changes: 27 additions & 5 deletions blocks/Config/normalizeConfigValue.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,30 @@ const asMetadata = (value) => {
throw new Error('Invalid metadata value. Must be an object or function.');
};

/** @param {unknown} value */
const asLocaleDefinitionOverride = (value) => {
/**
* @template {{}} T
* @param {unknown} value
* @returns {T}
*/
const asObject = (value) => {
if (typeof value === 'object') {
return /** @type {import('../../types').LocaleDefinitionOverride} */ (value);
return /** @type {T} */ (value);
}

throw new Error('Invalid localeDefinitionOverride value. Must be an object.');
throw new Error('Invalid value. Must be an object.');
};

/**
* @template {Function} T
* @param {unknown} value
* @returns {T}
*/
const asFunction = (value) => {
if (typeof value === 'function') {
return /** @type {T} */ (value);
}

throw new Error('Invalid value. Must be a function.');
};

/**
Expand Down Expand Up @@ -116,7 +133,12 @@ const mapping = {
localeName: asString,

metadata: asMetadata,
localeDefinitionOverride: asLocaleDefinitionOverride,
localeDefinitionOverride: /** @type {typeof asObject<import('../../types').LocaleDefinitionOverride>} */ (asObject),
secureUploadsSignatureResolver:
/** @type {typeof asFunction<import('../../types').SecureUploadsSignatureResolver>} */ (asFunction),
secureDeliveryProxyUrlResolver:
/** @type {typeof asFunction<import('../../types').SecureDeliveryProxyUrlResolver>} */ (asFunction),

};

/**
Expand Down
2 changes: 1 addition & 1 deletion blocks/FileItem/FileItem.js
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,7 @@ export class FileItem extends UploaderBlock {
}

const fileInput = file || entry.getValue('externalUrl') || entry.getValue('uuid');
const baseUploadClientOptions = this.getUploadClientOptions();
const baseUploadClientOptions = await this.getUploadClientOptions();
/** @type {import('@uploadcare/upload-client').FileFromOptions} */
const uploadClientOptions = {
...baseUploadClientOptions,
Expand Down
35 changes: 35 additions & 0 deletions demo/preview-proxy/secure-delivery-proxy-url-resolver.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<!doctype html>
<base href="../../" />

<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="./solutions/file-uploader/regular/index.css" />
<script
async=""
src="https://cdn.skypack.dev/-/[email protected]/dist=es2020,mode=raw,min/dist/es-module-shims.js"
></script>
<script type="importmap">
{
"imports": {
"@symbiotejs/symbiote": "./node_modules/@symbiotejs/symbiote/build/symbiote.js",
"@uploadcare/upload-client": "./node_modules/@uploadcare/upload-client/dist/esm/index.browser.mjs",
"@uploadcare/image-shrink": "./node_modules/@uploadcare/image-shrink/dist/esm/index.browser.mjs"
}
}
</script>
<script src="./index.js" type="module"></script>
<script type="module">
import * as LR from './index.js';

LR.registerBlocks(LR);

const config = document.querySelector('lr-config');
config.secureDeliveryProxyUrlResolver = (previewUrl) => {
return `http://localhost:3000/preview?url=${encodeURIComponent(previewUrl)}`
};
</script>
</head>

<lr-file-uploader-regular ctx-name="my-uploader"></lr-file-uploader-regular>
<lr-config ctx-name="my-uploader" pubkey="demopublickey"></lr-config>
<lr-upload-ctx-provider ctx-name="my-uploader"></lr-upload-ctx-provider>
34 changes: 34 additions & 0 deletions demo/preview-proxy/secure-delivery-proxy-url-template.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<!doctype html>
<base href="../../" />

<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="./solutions/file-uploader/regular/index.css" />
<script
async=""
src="https://cdn.skypack.dev/-/[email protected]/dist=es2020,mode=raw,min/dist/es-module-shims.js"
></script>
<script type="importmap">
{
"imports": {
"@symbiotejs/symbiote": "./node_modules/@symbiotejs/symbiote/build/symbiote.js",
"@uploadcare/upload-client": "./node_modules/@uploadcare/upload-client/dist/esm/index.browser.mjs",
"@uploadcare/image-shrink": "./node_modules/@uploadcare/image-shrink/dist/esm/index.browser.mjs"
}
}
</script>
<script src="./index.js" type="module"></script>
<script type="module">
import * as LR from './index.js';

LR.registerBlocks(LR);
</script>
</head>

<lr-file-uploader-regular ctx-name="my-uploader"></lr-file-uploader-regular>
<lr-config
ctx-name="my-uploader"
pubkey="demopublickey"
secure-delivery-proxy="http://localhost:3000/preview?url={{previewUrl}}"
></lr-config>
<lr-upload-ctx-provider ctx-name="my-uploader"></lr-upload-ctx-provider>
File renamed without changes.
43 changes: 43 additions & 0 deletions demo/secure-uploads.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<!doctype html>
<base href="../../" />

<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="./solutions/file-uploader/regular/index.css" />
<script
async=""
src="https://cdn.skypack.dev/-/[email protected]/dist=es2020,mode=raw,min/dist/es-module-shims.js"
></script>
<script type="importmap">
{
"imports": {
"@symbiotejs/symbiote": "./node_modules/@symbiotejs/symbiote/build/symbiote.js",
"@uploadcare/upload-client": "./node_modules/@uploadcare/upload-client/dist/esm/index.browser.mjs",
"@uploadcare/image-shrink": "./node_modules/@uploadcare/image-shrink/dist/esm/index.browser.mjs"
}
}
</script>
<script src="./index.js" type="module"></script>
<script type="module">
import * as LR from './index.js';

LR.registerBlocks(LR);

const config = document.querySelector('lr-config');
config.secureUploadsSignatureResolver = async () => {
return {
secureSignature: '41d3c05a1d9bfd4493186a5fd78f02719b6cb4363f55a52e235729a1649737b7',
secureExpire: '1715857665',
};
};
</script>
</head>

<lr-file-uploader-regular ctx-name="my-uploader"></lr-file-uploader-regular>
<lr-config
ctx-name="my-uploader"
pubkey="370313830c541a8bb21b"
secureSignature=""
secureExpire=""
></lr-config>
<lr-upload-ctx-provider ctx-name="my-uploader"></lr-upload-ctx-provider>
Loading
Loading