Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
10 changes: 6 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,13 +108,15 @@ await requestSupply(client, listing, { idempotencyKey: supplyIntentKey });

| SDK 函式 | 共用 operation ID | 一致性 |
| --- | --- | --- |
| `loadStorefront` | `listCatalog`, `listStores`, `listListings` | 從目前 session 讀取;依 storeId 篩選並排除不屬於已回傳商店的選品 |
| `loadStorefront` | `listCatalog`, `listStores`, `listListings` | 從目前 session 讀取;目錄依 `next_offset` 每頁最多 50 筆讀完,依 storeId 篩選並排除不屬於已回傳商店的選品 |
| `createStore` | `createStore` | 明確傳入 idempotency key |
| `selectProduct` | `createListing` | 保存 exact offer version;明確傳入 idempotency key |
| `requestSupply` | `requestSupply` | 傳送 listing ID、已審閱 snapshot digest、aggregate version 與相同重試 key |

API 驗證真正的使用者/社群/商店所有權。SDK 的篩選只是避免版面誤混資料,不是新的授權邊界。API 的拒絕、衝突與錯誤原樣交回 caller;SDK 不自動重試或生成新命令身分。版本衝突後重新讀取並讓人確認,新的操作才使用新 key。

目錄讀取到 `next_offset: null` 才回傳完整工作區;後續任何一頁失敗,整次讀取會失敗,不把已取得的前幾頁當成完整目錄。空目錄仍正常回傳。使用更新後的 pinned client 核對平台協定,不略過版本相容性檢查。

供貨量是 snapshot 記錄,沒有庫存保留;`accepted` 是內部供貨演練確認,沒有代表完成正式簽署、QC 或可收款。所有目前顯示金額遵循中央契約的 1/100 單位。

## 後續公開商店
Expand All @@ -132,12 +134,12 @@ import { loadConnectedStorefront } from './src/index.mjs';
const workspace = await loadConnectedStorefront({ origin: 'https://freetwai.com', token });
```

The token comes from the existing member-approved connection and must stay outside the repository. The existing session-based SDK and preview v1 bundle are unchanged. `consumer-libraries.lock.json` pins this new shared library separately; it is source provenance, not release approval or complete runtime coverage. Verify against an independently selected source SHA:
The token comes from the existing member-approved connection and must stay outside the repository. The session-based SDK uses its separately pinned preview bundle; `consumer-libraries.lock.json` preserves the shared read library's independent source pin. This is source provenance, not release approval or complete runtime coverage. Verify against an independently selected source SHA:

```sh
node scripts/verify-consumer-libraries.mjs FreeTWAI-AI/freedom-storefront EXPECTED_PLATFORM_SHA --source-root /path/to/freedom-platform
node scripts/verify-consumer-libraries.mjs FreeTWAI/freedom-storefront EXPECTED_PLATFORM_SHA --source-root /path/to/freedom-platform
```

The repository argument is the historical provenance identity required by this pinned verifier and `consumer-libraries.lock.json`. Current GitHub and clone URLs use `FreeTWAI`.
The verifier accepts the current `FreeTWAI` repository identity while preserving the historical identity recorded in the library lock. Use that library's independently selected source SHA, not the preview bundle's source SHA.

After the exact source commit is publicly available, use `--remote` instead of `--source-root /path/to/freedom-platform`.
8 changes: 4 additions & 4 deletions contracts.lock.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"format": "freedom.contract-pin/v1",
"source_repository": "FreeTWAI-AI/freedom-platform",
"source_commit": "b221d2ba1bcf014dc785e95212455ba6f157ec6d",
"source_repository": "FreeTWAI/freedom-platform",
"source_commit": "e09fe06f3393c64e04afd6475dd6c427b3dab127",
"bundle_path": "contracts/preview/v1",
"protocol": "freedom.preview/v1",
"protocol_sha256": "fe2ee45447f4a5e92c10e22307dee3b380d028acca04bac5278d3aeca0da7b3e",
"bundle_sha256": "835e9a898d3c10eaabd16c92cfeb25eae050f658814da3aec055f019a7245d3d"
"protocol_sha256": "41378c3b723f739cefdf8c53a82238b1e5d69cc13cdbf63b33a80d8080c807b2",
"bundle_sha256": "5272d0e15073dda83e9811f116a8f0c538bd843a7b0f56baccacc4a416eee19f"
}
12 changes: 10 additions & 2 deletions packages/storefront-sdk/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,23 @@ export async function loadStorefront(client, { storeId } = {}) {
port(client);
if (storeId !== undefined && (typeof storeId !== 'string' || !storeId.trim())) throw new TypeError('storeId must be a non-empty string.');
const [catalogResponse, storesResponse, listingsResponse] = await Promise.all([
client.call('listCatalog'), client.call('listStores'), client.call('listListings'),
client.call('listCatalog', { query: { limit: 50, offset: 0 } }), client.call('listStores'), client.call('listListings'),
]);
const catalog = rows(catalogResponse, 'listCatalog');
const catalog = [...rows(catalogResponse, 'listCatalog')];
const availableStores = rows(storesResponse, 'listStores');
const availableListings = rows(listingsResponse, 'listListings');
const stores = storeId === undefined ? availableStores : availableStores.filter(store => store.store_id === storeId);
if (storeId !== undefined && stores.length !== 1) throw new Error('Requested store is unavailable in the current authenticated workspace.');
const visibleStoreIds = new Set(stores.map(store => store.store_id));
const listings = availableListings.filter(listing => visibleStoreIds.has(listing.store_id));
let page = catalogResponse, offset = 0;
while (page.next_offset !== null) {
const nextOffset = page.next_offset;
if (!Number.isSafeInteger(nextOffset) || nextOffset <= offset) throw new TypeError('listCatalog returned an invalid next_offset.');
page = await client.call('listCatalog', { query: { limit: 50, offset: nextOffset } });
catalog.push(...rows(page, 'listCatalog'));
offset = nextOffset;
}
return structuredClone({
schema_version: '1', mode: 'internal_preview', generated_at: new Date().toISOString(),
store_id: storeId ?? null, catalog, stores, listings,
Expand Down
3 changes: 3 additions & 0 deletions scripts/freedom.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// Thin consumer entrypoint; implementation is exported from the central repo.
import { runFreedomCli } from '../vendor/freedom-tooling/packages/contribution-tools/cli.mjs';
process.exitCode = await runFreedomCli();
26 changes: 3 additions & 23 deletions scripts/verify-contracts.mjs
Original file line number Diff line number Diff line change
@@ -1,23 +1,3 @@
// Copied verifier, no writes. Contract authoring stays in freedom-platform.
import {readFile,readdir,lstat} from 'node:fs/promises';
import {createHash} from 'node:crypto';
import {resolve} from 'node:path';
const root=process.cwd(),vendor=resolve(root,'vendor/freedom-platform');
const lock=JSON.parse(await readFile(resolve(root,'contracts.lock.json'),'utf8'));
const hash=data=>createHash('sha256').update(data).digest('hex');
if(!['FreeTWAI-AI/freedom-platform','FreeTWAI/freedom-platform'].includes(lock.source_repository)||!/^[a-f0-9]{40}$/.test(lock.source_commit)||lock.bundle_path!=='contracts/preview/v1')throw Error('Invalid canonical contract source');
const manifestBytes=await readFile(resolve(vendor,'bundle.json'));
if(hash(manifestBytes)!==lock.bundle_sha256)throw Error('Contract bundle digest differs from lock');
const bundle=JSON.parse(manifestBytes);if(bundle.protocol!==lock.protocol||bundle.protocol_sha256!==lock.protocol_sha256)throw Error('Protocol identity differs from lock');
const expected=new Set(['bundle.json',...Object.keys(bundle.files)]);
async function walk(dir,prefix=''){for(const item of await readdir(dir,{withFileTypes:true})){const rel=prefix+item.name;if(item.isSymbolicLink())throw Error('Symlink not allowed in bundle');if(item.isDirectory())await walk(resolve(dir,item.name),rel+'/');else if(!expected.has(rel))throw Error(`Unexpected bundle file ${rel}`);}}
await walk(vendor);
const remote=process.argv.includes('--remote');
for(const file of expected){
if(file.split('/').some(p=>!p||p==='.'||p==='..')||!/^[-a-zA-Z0-9_./]+$/.test(file))throw Error('Invalid artifact path');
const path=resolve(vendor,file);if(!(await lstat(path)).isFile())throw Error('Artifact must be a regular file');
const local=await readFile(path);const declared=file==='bundle.json'?{sha256:lock.bundle_sha256}:bundle.files[file];
if(hash(local)!==declared.sha256||(declared.bytes!==undefined&&local.byteLength!==declared.bytes))throw Error(`Modified canonical artifact ${file}`);
if(remote){const url=`https://raw.githubusercontent.com/FreeTWAI/freedom-platform/${lock.source_commit}/${lock.bundle_path}/${file}`;const response=await fetch(url,{redirect:'error',signal:AbortSignal.timeout(20000)});if(!response.ok)throw Error(`Cannot verify pinned artifact ${file}: ${response.status}`);const bytes=new Uint8Array(await response.arrayBuffer());if(bytes.byteLength>2_000_000||hash(bytes)!==declared.sha256)throw Error(`Pinned upstream differs: ${file}`);}
}
console.log(`Contract ${lock.protocol} at ${lock.source_commit.slice(0,12)}: ${expected.size} artifacts verified${remote?' against pinned GitHub source':''}.`);
// Consumer entrypoint; exported together with the central tooling, not a forked verifier.
import { runPinCli } from '../vendor/freedom-tooling/packages/contribution-tools/pin-cli.mjs';
process.exitCode = await runPinCli();
47 changes: 46 additions & 1 deletion tests/storefront.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { loadStorefront, createStore, selectProduct, requestSupply } from '../pa

function workspace() {
const data = {
listCatalog: { items: [{ product_id: 'product-a', current_offer: { offer_version_id: 'offer-v2' } }] },
listCatalog: { items: [{ product_id: 'product-a', current_offer: { offer_version_id: 'offer-v2' } }], next_offset: null },
listStores: { items: [{ store_id: 'store-a' }, { store_id: 'store-b' }] },
listListings: { items: [{ listing_id: 'a', store_id: 'store-a' }, { listing_id: 'b', store_id: 'store-b' }, { listing_id: 'foreign', store_id: 'foreign-store' }] },
};
Expand All @@ -31,6 +31,51 @@ test('workspace without selection includes only listings attached to returned st
assert.deepEqual((await loadStorefront(client)).listings.map(row => row.listing_id), ['a', 'b']);
});

test('workspace reads the complete catalog, including empty and exact-page endings', async () => {
for (const count of [0, 50, 101]) {
const { data } = workspace();
const products = Array.from({ length: count }, (_, index) => ({ product_id: `product-${index}` }));
const offsets = [], pages = [];
const client = { async call(operation, options) {
if (operation !== 'listCatalog') return data[operation];
assert.equal(options.query.limit, 50);
const { offset } = options.query;
offsets.push(offset);
const page = { items: products.slice(offset, offset + 50), next_offset: offset + 50 < count ? offset + 50 : null };
pages.push(page);
return page;
} };
const result = await loadStorefront(client, { storeId: 'store-a' });
assert.deepEqual(result.catalog, products);
assert.deepEqual(offsets, count > 50 ? [0, 50, 100] : [0]);
assert.equal(pages[0].items.length, Math.min(count, 50));
assert.deepEqual(result.listings.map(row => row.listing_id), ['a']);
}
});

test('a later catalog authorization failure rejects the whole workspace without retry', async () => {
const { data } = workspace();
const failure = Object.assign(new Error('session expired'), { status: 401 });
const offsets = [];
const client = { async call(operation, options) {
if (operation !== 'listCatalog') return data[operation];
offsets.push(options.query.offset);
if (options.query.offset === 0) return { items: data.listCatalog.items, next_offset: 50 };
throw failure;
} };
await assert.rejects(loadStorefront(client), error => error === failure);
assert.deepEqual(offsets, [0, 50]);
});

test('invalid catalog continuation fails instead of returning partial data or looping', async () => {
for (const next_offset of [undefined, 0, -1, '50', 1.5]) {
const { client, data, calls } = workspace();
data.listCatalog.next_offset = next_offset;
await assert.rejects(loadStorefront(client), /next_offset/);
assert.equal(calls.filter(row => row.operation === 'listCatalog').length, 1);
}
});

test('unknown store and invalid API response fail closed', async () => {
const { client, data } = workspace();
await assert.rejects(loadStorefront(client, { storeId: 'foreign-store' }), /unavailable/);
Expand Down
24 changes: 12 additions & 12 deletions vendor/freedom-platform/bundle.json
Original file line number Diff line number Diff line change
@@ -1,32 +1,32 @@
{
"format": "freedom.contract-bundle/v1",
"protocol": "freedom.preview/v1",
"revision": "0.3.0",
"protocol_sha256": "fe2ee45447f4a5e92c10e22307dee3b380d028acca04bac5278d3aeca0da7b3e",
"revision": "0.4.1",
"protocol_sha256": "41378c3b723f739cefdf8c53a82238b1e5d69cc13cdbf63b33a80d8080c807b2",
"files": {
"openapi.json": {
"sha256": "898228553caf72955943a203a58ed0a06f8a36bc7266541593710c9f31d5dc8e",
"bytes": 80211
"sha256": "3c536da7dbb75b692c83ae69976b0d782793f7b8383e69f65db97b3e4769a338",
"bytes": 84953
},
"metadata.json": {
"sha256": "465ce597d48b6e3cbce3569161706f82c9a4da8240dcd6a1a43ba7273bd158a3",
"bytes": 942
"sha256": "4c6ef9306fc33aad342f3f344272b6b0abbe8aaade3ffdeb7cc486376b23903f",
"bytes": 963
},
"protocol.mjs": {
"sha256": "dbbf667907513ba16886de3f5c9183169aadca223cddfd7286ba10d471675c41",
"bytes": 35961
"sha256": "1df7d91e0a5849f4c2d34a471e15ccfdd99bb62ae4f6bf941ceea729eea2ad34",
"bytes": 39341
},
"client.mjs": {
"sha256": "37138679c14966d3c6fb79a6766e63ad20875fea4f8d11f1dfd0e522737431f6",
"bytes": 6197
"sha256": "f9b96369adc16be27febd0c63f73e4ae622f3738304240d0f801a890f18de50b",
"bytes": 7844
},
"schema.mjs": {
"sha256": "337c263e292b5f62484b73fb0a522f7a88df94bf3f3b3e18d26f2299a0b49eeb",
"bytes": 2321
},
"client.d.mts": {
"sha256": "0ad63e3bb690e60401e0a6a5b70ee2a5d807a9c05a4d907cd044f364d122c341",
"bytes": 8252
"sha256": "ec7043bf91335f31f97a1e8fd01b75aa94e12f4d5b535595d2997529ceb59792",
"bytes": 9130
},
"schemas/project-manifest.schema.json": {
"sha256": "dc845236fcac6160e3c7adc2690690dc24bd7c2553ac599013c03f745d400345",
Expand Down
Loading
Loading