Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5bef6291e8 | ||
|
|
9724358c89 | ||
|
|
7555cefccb | ||
|
|
04621223fd | ||
|
|
e5016d8b86 | ||
|
|
b455dc6286 | ||
|
|
338b6ebbd0 |
No files matched your search
@@ -19,8 +19,8 @@ threads, create and self-assign issues, discover, claim, and release issue assig
|
||||
list repository labels and open milestones, set or clear due dates on assigned issues, create issue comments, close assigned issues,
|
||||
inspect/comment on assigned pull
|
||||
requests, merge assigned pull requests, and submit pull-request reviews.
|
||||
Assigned-issue comments can include one PNG, JPEG, or WebP screenshot; the mobile composer automatically optimizes oversized screenshots on-device to fit the 2 MB upload boundary while leaving already-valid files unchanged.
|
||||
For online delivery, the screenshot uploads before the comment is posted; validation or upload
|
||||
Assigned-issue and assigned-pull-request comments can include one PNG, JPEG, or WebP screenshot; each mobile composer automatically optimizes oversized screenshots on-device to fit the 2 MB upload boundary while leaving already-valid files unchanged.
|
||||
For online delivery, the screenshot uploads before the comment is posted—to the exact assigned issue or pull request—and produces one Markdown comment; validation or upload
|
||||
failures keep both the typed comment and removable preview available for retry. Offline screenshot comments
|
||||
admit their text and image bytes to IndexedDB before confirmation, keep only bounded metadata in
|
||||
localStorage, and use checkpointed upload/comment identities so reconnect retries cannot duplicate
|
||||
@@ -212,16 +212,17 @@ session's last explicit activity. Existing two-column registries are migrated in
|
||||
place, their live sessions remain valid, and their idle clock starts at migration.
|
||||
|
||||
The same sheet includes **Security activity**, a reverse-chronological journal of
|
||||
successful token/passkey sign-ins, sign-outs, remote device revocations, issue
|
||||
closures, and pull-request merges. The separate SQLite journal retains at most
|
||||
10,000 events for 90 days and stores only bounded device labels and action targets.
|
||||
It never stores access tokens, cookies, session/CSRF values, credential IDs, raw
|
||||
network addresses, request bodies, or comment content. Keep its database on the
|
||||
same class of persistent, writable storage as the session registry. Before a
|
||||
session revocation or issue closure, the journal durably reserves a pending event;
|
||||
if that reservation fails, the destructive action does not begin. A successful
|
||||
action remains truthfully reported even if its event cannot immediately be finalized,
|
||||
and the activity sheet marks that durable record as **Outcome confirmation pending**.
|
||||
successful token/passkey sign-ins, passkey enrollments, sign-outs, remote device
|
||||
revocations, issue closures, and pull-request merges. The separate SQLite journal
|
||||
retains at most 10,000 events for 90 days and stores only bounded device labels and
|
||||
action targets. It never stores access tokens, cookies, session/CSRF values,
|
||||
credential IDs, public keys, challenges, attestation data, raw network addresses,
|
||||
request bodies, or comment content. Keep its database on the same class of persistent,
|
||||
writable storage as the session registry. Before passkey credential creation, session
|
||||
revocation, or issue closure, the journal durably reserves a pending event; if that
|
||||
reservation fails, the consequential action does not begin. A successful action
|
||||
remains truthfully reported even if its event cannot immediately be finalized, and
|
||||
the activity sheet marks that durable record as **Outcome confirmation pending**.
|
||||
|
||||
After token bootstrap, **Active devices → Add a passkey for this device** enrolls a
|
||||
WebAuthn credential with required user verification. That device can then sign in
|
||||
|
||||
@@ -75,7 +75,7 @@ function createAuthoredOutbox({ storage, fetchJson, coordinator, backgroundSync,
|
||||
status: 'queued',
|
||||
queuedAt: Number(now()),
|
||||
...(message.kind === 'update-reply-read' ? { replyConfirmed: message.replyConfirmed === true } : {}),
|
||||
...(message.kind === 'issue-comment' && message.attachment ? {
|
||||
...(['issue-comment', 'pull-comment'].includes(message.kind) && message.attachment ? {
|
||||
attachment: {
|
||||
filename: String(message.attachment.filename || ''),
|
||||
contentType: String(message.attachment.contentType || ''),
|
||||
|
||||
@@ -510,11 +510,12 @@ function createBackgroundIssueSync({
|
||||
|
||||
async function deliverScreenshotComment(item) {
|
||||
const repository = String(item.repository || '').split('/').map(encodeURIComponent).join('/');
|
||||
const resource = item.kind === 'pull-comment' ? 'pulls' : 'issues';
|
||||
let attachmentMarkdown = item.attachmentMarkdown;
|
||||
if (!attachmentMarkdown) {
|
||||
const uploaded = await requestStage(
|
||||
item,
|
||||
base + 'api/v1/repos/' + repository + '/issues/' + encodeURIComponent(item.number) + '/attachments',
|
||||
base + 'api/v1/repos/' + repository + '/' + resource + '/' + encodeURIComponent(item.number) + '/attachments',
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -535,7 +536,7 @@ function createBackgroundIssueSync({
|
||||
const text = String(item.body || '').trim();
|
||||
return requestStage(
|
||||
item,
|
||||
base + 'api/v1/repos/' + repository + '/issues/' + encodeURIComponent(item.number) + '/comments',
|
||||
base + 'api/v1/repos/' + repository + '/' + resource + '/' + encodeURIComponent(item.number) + '/comments',
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -551,7 +552,7 @@ function createBackgroundIssueSync({
|
||||
const request = deliveryRequest(item);
|
||||
try {
|
||||
const delivered = item.kind === 'update-reply-read' ? await deliverReplyRead(item) :
|
||||
item.attachment && item.kind === 'issue-comment' ?
|
||||
item.attachment && ['issue-comment', 'pull-comment'].includes(item.kind) ?
|
||||
await deliverScreenshotComment(item) : item.attachment && !item.kind ?
|
||||
await deliverIssueCapture(item) : await requestStage(item, request.url, request.options);
|
||||
if (item.kind === 'issue-close' && delivered?.state !== 'closed') {
|
||||
|
||||
@@ -232,6 +232,18 @@ textarea { resize: vertical; min-height: 120px; }
|
||||
.review-diff-note, .review-diff-empty { display:block; padding:8px; color:#fcd34d; white-space:normal; }
|
||||
.review-action { min-height:44px; }
|
||||
.review-retry { min-height:44px; margin-top:10px; }
|
||||
.ci-checks { max-width:100%; margin:10px 0; border:1px solid #2a496e; border-radius:10px; overflow:hidden; }
|
||||
.ci-checks > summary { min-height:44px; display:flex; align-items:center; justify-content:space-between; gap:8px; padding:0 10px; cursor:pointer; }
|
||||
.ci-checks > summary .small { min-width:0; overflow-wrap:anywhere; text-align:right; }
|
||||
.ci-check-refresh { width:100%; min-height:44px; margin-bottom:6px; }
|
||||
.ci-check-list { display:grid; gap:6px; min-width:0; padding:0 8px 8px; }
|
||||
.ci-check { min-width:0; display:grid; grid-template-columns:minmax(0,1fr) auto; align-items:center; gap:8px; padding:8px; border:1px solid #203a5c; border-radius:8px; }
|
||||
.ci-check-failure, .ci-check-error { border-color:#dc2626; background:rgba(127,29,29,.22); }
|
||||
.ci-check-pending { border-color:#d97706; background:rgba(120,53,15,.2); }
|
||||
.ci-check-success { border-color:#15803d; }
|
||||
.ci-check-copy { min-width:0; display:grid; gap:3px; overflow-wrap:anywhere; }
|
||||
.ci-check-copy strong, .ci-check-copy span { min-width:0; overflow-wrap:anywhere; }
|
||||
.ci-check-link { min-height:44px; display:flex; align-items:center; justify-content:center; padding:0 10px; border:1px solid #60a5fa; border-radius:8px; white-space:nowrap; }
|
||||
.update-sheet { position:fixed; inset:0; z-index:55; display:none; justify-content:flex-end; background:rgba(5,12,21,.72); backdrop-filter:blur(4px); }
|
||||
.update-sheet.open { display:flex; }
|
||||
.update-sheet-panel { width:min(560px,100%); height:100%; overflow:auto; padding:18px; background:#0b1526; border-left:1px solid #2a496e; }
|
||||
|
||||
+152
-30
@@ -303,6 +303,27 @@
|
||||
);
|
||||
},
|
||||
});
|
||||
const pullAttachmentController = issueAttachment.mount({
|
||||
input: qs('#pull-attachment'),
|
||||
preview: qs('#pull-attachment-preview'),
|
||||
image: qs('#pull-attachment-image'),
|
||||
meta: qs('#pull-attachment-meta'),
|
||||
remove: qs('#remove-pull-attachment'),
|
||||
status: qs('#pull-comment-status'),
|
||||
createObjectURL: file => URL.createObjectURL(file),
|
||||
revokeObjectURL: url => URL.revokeObjectURL(url),
|
||||
upload: payload => {
|
||||
const repository = payload.repository.split('/').map(encodeURIComponent).join('/');
|
||||
return fetchReviewJson(
|
||||
'api/v1/repos/' + repository + '/pulls/' + encodeURIComponent(payload.number) + '/attachments',
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { Accept:'application/json', 'Idempotency-Key':payload.operation_id },
|
||||
body: issueAttachment.multipart(payload),
|
||||
},
|
||||
);
|
||||
},
|
||||
});
|
||||
const createIssueAttachmentController = issueAttachment.mount({
|
||||
input: qs('#create-issue-attachment'),
|
||||
preview: qs('#create-issue-attachment-preview'),
|
||||
@@ -2272,7 +2293,15 @@
|
||||
if (issueTrigger?.isConnected) issueTrigger.focus();
|
||||
}
|
||||
|
||||
function renderCheckSection(prefix, detail, offline = false) {
|
||||
const rendered = createReviewController.renderChecks(detail?.checks, escapeHtml, { offline });
|
||||
qs('#' + prefix + '-checks-summary').textContent = rendered.summary;
|
||||
qs('#' + prefix + '-check-list').innerHTML = rendered.html || '<div class="muted">No individual checks were reported.</div>';
|
||||
qs('#' + prefix + '-checks').open = rendered.expanded;
|
||||
}
|
||||
|
||||
function renderPullReview(detail, focusFilename = null) {
|
||||
renderCheckSection('pull', detail);
|
||||
pullReviewState = pullController.reviewState(selectedPull, detail);
|
||||
qs('#pull-review-progress').textContent = pullReviewState.total ?
|
||||
pullReviewState.reviewed.length + ' of ' + pullReviewState.total + ' files reviewed' : 'No changed files to review';
|
||||
@@ -2319,7 +2348,7 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function loadPullReview() {
|
||||
async function loadPullReview({ refresh = false } = {}) {
|
||||
if (!selectedPull || !selectedPullDetail?.head_sha) return;
|
||||
const item = selectedPull;
|
||||
const readDetail = selectedPullDetail;
|
||||
@@ -2327,7 +2356,7 @@
|
||||
qs('#pull-review-retry').hidden = true;
|
||||
qs('#merge-pull').disabled = true;
|
||||
try {
|
||||
const review = await pullController.loadReview(item, readDetail.head_sha);
|
||||
const review = await pullController.loadReview(item, readDetail.head_sha, { refresh });
|
||||
if (selectedPull !== item) return;
|
||||
selectedPullDetail = { ...readDetail, ...review };
|
||||
qs('#pull-ci-state').textContent = 'CI ' + (review.ci_state || 'unknown');
|
||||
@@ -2343,8 +2372,14 @@
|
||||
}
|
||||
}
|
||||
|
||||
function sameWorkTarget(left, right) {
|
||||
return Boolean(left && right && left.repository === right.repository &&
|
||||
Number(left.number) === Number(right.number));
|
||||
}
|
||||
|
||||
async function openPullSheet(item, trigger, offlineDetail = null) {
|
||||
if (!item) return;
|
||||
if (!sameWorkTarget(selectedPull, item)) pullAttachmentController.clear();
|
||||
qs('#pull-review').inert = false;
|
||||
selectedPull = item;
|
||||
pullMentions.dismiss();
|
||||
@@ -2369,6 +2404,9 @@
|
||||
qs('#pull-comment').value = pullController.loadDraft(item);
|
||||
qs('#pull-comment-status').textContent = '';
|
||||
qs('#pull-ci-state').textContent = 'CI unknown';
|
||||
qs('#pull-checks-summary').textContent = 'Not loaded';
|
||||
qs('#pull-check-list').textContent = '';
|
||||
qs('#pull-checks').open = false;
|
||||
qs('#pull-merge-state').textContent = 'Review data not loaded';
|
||||
qs('#merge-pull').disabled = true;
|
||||
qs('#merge-pull').textContent = workSession.active() ? 'Merge & next' : 'Merge';
|
||||
@@ -2407,6 +2445,7 @@
|
||||
return;
|
||||
}
|
||||
mobileComposerViewport.close(qs('#pull-sheet .pull-sheet-panel'));
|
||||
pullAttachmentController.clear();
|
||||
qs('#pull-sheet').classList.remove('open');
|
||||
selectedPull = null;
|
||||
selectedPullDetail = null;
|
||||
@@ -2918,6 +2957,11 @@
|
||||
qs('#review-handoff-status').textContent = '';
|
||||
qs('#review-submit-status').textContent = '';
|
||||
qs('#continue-review-to-merge').hidden = true;
|
||||
qs('#review-ci-state').textContent = 'CI unknown';
|
||||
qs('#review-checks-summary').textContent = cachedDetail ? 'Last known · loading' : 'Loading';
|
||||
qs('#review-check-list').textContent = '';
|
||||
qs('#review-checks').open = false;
|
||||
qs('#refresh-review-checks').disabled = offlineReview;
|
||||
qs('#submit-review').disabled = true;
|
||||
qs('#submit-review').textContent = offlineReview && reviewingActiveTodayItem() ? 'Queue review & next' :
|
||||
(offlineReview ? 'Queue review for reconnect' : 'Submit review');
|
||||
@@ -2931,6 +2975,7 @@
|
||||
if (selectedReview !== item) return;
|
||||
qs('#review-sheet-body').innerHTML = renderMarkdown(detail.body || 'No description provided.');
|
||||
qs('#review-ci-state').textContent = 'CI ' + (detail.ci_state || 'unknown');
|
||||
renderCheckSection('review', detail, offlineReview);
|
||||
qs('#review-files').innerHTML = (detail.files || []).length ? detail.files.map((file, index) =>
|
||||
createReviewController.renderDiffFile(file, index, escapeHtml)
|
||||
).join('') : '<div>No changed files reported.</div>';
|
||||
@@ -3929,13 +3974,32 @@
|
||||
return admission;
|
||||
}
|
||||
|
||||
async function queuePullScreenshotComment(item, body, operationId, advance = false, deliver = false) {
|
||||
const message = {
|
||||
kind: 'pull-comment', repository: item.repository, number: item.number, body,
|
||||
operationId: operationId || globalThis.crypto?.randomUUID?.() || String(Date.now()),
|
||||
attachment: await pullAttachmentController.serialize(),
|
||||
};
|
||||
if (advance) return await pullCommentNext.admit(item, message);
|
||||
const admission = await authoredOutbox.enqueueDurably(message);
|
||||
if (deliver) {
|
||||
const delivery = await authoredOutbox.retry(admission.item.id, activeFlushLogin);
|
||||
return { ...admission, delivered: delivery.confirmed?.[0] || null };
|
||||
}
|
||||
pullController.saveDraft(item, '');
|
||||
if (selectedPull === item) qs('#pull-comment').value = '';
|
||||
return admission;
|
||||
}
|
||||
|
||||
async function submitCommentAndNext(kind) {
|
||||
const item = kind === 'issue' ? selectedIssue : selectedPull;
|
||||
if (!item || !workSession.checkpointed(item)) return;
|
||||
const textarea = qs('#' + kind + '-comment');
|
||||
const status = qs('#' + kind + '-comment-status');
|
||||
const body = textarea.value.trim();
|
||||
if (!body && (kind !== 'issue' || !issueAttachmentController.state())) {
|
||||
const attachmentController = kind === 'issue' ? issueAttachmentController : pullAttachmentController;
|
||||
const queueScreenshot = kind === 'issue' ? queueIssueScreenshotComment : queuePullScreenshotComment;
|
||||
if (!body && !attachmentController.state()) {
|
||||
status.textContent = 'Write a comment before posting.';
|
||||
textarea.focus();
|
||||
return;
|
||||
@@ -3947,26 +4011,28 @@
|
||||
item.repository + '#' + item.number + ':operation');
|
||||
postButton.disabled = true;
|
||||
nextButton.disabled = true;
|
||||
status.textContent = kind === 'issue' && issueAttachmentController.state() ?
|
||||
attachmentController.setBusy(true);
|
||||
status.textContent = attachmentController.state() ?
|
||||
'Uploading screenshot before opening next…' : 'Posting comment and opening next…';
|
||||
try {
|
||||
let result;
|
||||
if (kind === 'issue' && issueAttachmentController.state() && navigator.onLine === false) {
|
||||
result = await queueIssueScreenshotComment(item, body, operationId(), true);
|
||||
if (attachmentController.state() && (kind === 'pull' || navigator.onLine === false)) {
|
||||
result = await queueScreenshot(item, body, operationId(), true);
|
||||
} else {
|
||||
let preparedBody;
|
||||
try {
|
||||
preparedBody = kind === 'issue' ?
|
||||
await issueAttachmentController.prepareComment(item, body) : body;
|
||||
await issueAttachmentController.prepareComment(item, body) :
|
||||
await pullAttachmentController.prepareComment(item, body);
|
||||
} catch (error) {
|
||||
if (kind !== 'issue' || !issueAttachmentController.state() || !canQueueMessage(error)) throw error;
|
||||
result = await queueIssueScreenshotComment(item, body, operationId(), true);
|
||||
if (!attachmentController.state() || !canQueueMessage(error)) throw error;
|
||||
result = await queueScreenshot(item, body, operationId(), true);
|
||||
}
|
||||
if (!result) result = await controller.submit(item, preparedBody, operationId);
|
||||
}
|
||||
const stillOpen = kind === 'issue' ? selectedIssue === item : selectedPull === item;
|
||||
if (!stillOpen) return;
|
||||
if (kind === 'issue') issueAttachmentController.clear();
|
||||
attachmentController.clear();
|
||||
if (!result.completed) status.textContent = 'Comment saved, but Today still needs completion.';
|
||||
else if (result.delivery === 'posted') status.textContent = 'Comment posted.';
|
||||
else if (result.background) status.textContent = 'Queued for sync when the connection returns.';
|
||||
@@ -3975,6 +4041,7 @@
|
||||
status.textContent = error.message + ' Your draft, screenshot, and Today position are safe; retry.';
|
||||
textarea.focus();
|
||||
} finally {
|
||||
attachmentController.setBusy(false);
|
||||
postButton.disabled = false;
|
||||
nextButton.disabled = false;
|
||||
}
|
||||
@@ -4212,6 +4279,13 @@
|
||||
if (event.currentTarget.open) loadPullReview();
|
||||
});
|
||||
qs('#pull-review-retry').addEventListener('click', loadPullReview);
|
||||
qs('#refresh-pull-checks').addEventListener('click', async () => {
|
||||
const button = qs('#refresh-pull-checks');
|
||||
button.disabled = true;
|
||||
qs('#pull-checks-summary').textContent = 'Refreshing…';
|
||||
try { await loadPullReview({ refresh: true }); }
|
||||
finally { button.disabled = false; }
|
||||
});
|
||||
qs('#next-unreviewed-pull-file').addEventListener('click', focusNextUnreviewedPullFile);
|
||||
qs('#load-older-pull-comments').addEventListener('click', async () => {
|
||||
if (!pullConversation) return;
|
||||
@@ -4234,39 +4308,68 @@
|
||||
});
|
||||
qs('#send-pull-comment').addEventListener('click', async () => {
|
||||
if (!selectedPull) return;
|
||||
const item = selectedPull;
|
||||
const body = qs('#pull-comment').value.trim();
|
||||
if (!body) {
|
||||
if (!body && !pullAttachmentController.state()) {
|
||||
qs('#pull-comment-status').textContent = 'Write a comment before posting.';
|
||||
qs('#pull-comment').focus();
|
||||
return;
|
||||
}
|
||||
const button = qs('#send-pull-comment');
|
||||
button.disabled = true;
|
||||
qs('#pull-comment-status').textContent = 'Posting comment…';
|
||||
pullAttachmentController.setBusy(true);
|
||||
qs('#pull-comment-status').textContent = pullAttachmentController.state() ?
|
||||
'Uploading screenshot…' : 'Posting comment…';
|
||||
const operationId = localStorage.getItem('stackchain.pull-comment.v1:' +
|
||||
item.repository + '#' + item.number + ':operation');
|
||||
let preparedBody;
|
||||
try {
|
||||
const comment = await pullController.comment(selectedPull, body);
|
||||
if (pullConversation) renderPullConversation(pullConversation.append(comment));
|
||||
qs('#pull-comment').value = '';
|
||||
if (pullAttachmentController.state()) {
|
||||
const admission = await queuePullScreenshotComment(item, body, operationId, false, true);
|
||||
refreshMyWorkView();
|
||||
pullController.saveDraft(item, '');
|
||||
if (selectedPull === item) {
|
||||
if (admission.delivered && pullConversation) {
|
||||
renderPullConversation(pullConversation.append(admission.delivered));
|
||||
}
|
||||
qs('#pull-comment').value = '';
|
||||
pullAttachmentController.clear();
|
||||
qs('#pull-comment-status').textContent = admission.delivered ? 'Comment posted.' :
|
||||
(admission.background ? 'Queued with screenshot for sync when the connection returns.' :
|
||||
'Saved with screenshot for next launch; background delivery unavailable.');
|
||||
}
|
||||
return;
|
||||
}
|
||||
preparedBody = body;
|
||||
const comment = await pullController.comment(item, preparedBody);
|
||||
if (selectedPull === item && pullConversation) renderPullConversation(pullConversation.append(comment));
|
||||
pullController.saveDraft(item, '');
|
||||
if (selectedPull === item) qs('#pull-comment').value = '';
|
||||
pullAttachmentController.clear();
|
||||
qs('#pull-comment-status').textContent = 'Comment posted.';
|
||||
} catch (error) {
|
||||
if (canQueueMessage(error)) {
|
||||
const operationId = localStorage.getItem('stackchain.pull-comment.v1:' + selectedPull.repository + '#' + selectedPull.number + ':operation');
|
||||
qs('#pull-comment-status').textContent = 'Saving for background delivery…';
|
||||
const admission = await authoredOutbox.enqueueDurably({ kind:'pull-comment', repository:selectedPull.repository,
|
||||
number:selectedPull.number, body, operationId });
|
||||
refreshMyWorkView();
|
||||
if (admission.background) {
|
||||
qs('#pull-comment').value = '';
|
||||
qs('#pull-comment-status').textContent = 'Queued for sync when the connection returns.';
|
||||
} else {
|
||||
qs('#pull-comment-status').textContent = 'Saved for next launch; background delivery unavailable.';
|
||||
qs('#pull-comment').focus();
|
||||
if (canQueueMessage(error) && !pullAttachmentController.state()) {
|
||||
try {
|
||||
qs('#pull-comment-status').textContent = 'Saving for background delivery…';
|
||||
const admission = await authoredOutbox.enqueueDurably({
|
||||
kind:'pull-comment', repository:item.repository, number:item.number,
|
||||
body:preparedBody ?? body, operationId,
|
||||
});
|
||||
pullController.saveDraft(item, '');
|
||||
if (selectedPull === item) qs('#pull-comment').value = '';
|
||||
refreshMyWorkView();
|
||||
qs('#pull-comment-status').textContent = admission.background ?
|
||||
'Queued for sync when the connection returns.' :
|
||||
'Saved for next launch; background delivery unavailable.';
|
||||
return;
|
||||
} catch (admissionError) {
|
||||
error = admissionError;
|
||||
}
|
||||
} else {
|
||||
qs('#pull-comment-status').textContent = error.message + ' Your draft is safe; retry.';
|
||||
qs('#pull-comment').focus();
|
||||
}
|
||||
qs('#pull-comment-status').textContent = error.message + ' Your comment and screenshot are safe; retry.';
|
||||
qs('#pull-comment').focus();
|
||||
} finally {
|
||||
pullAttachmentController.setBusy(false);
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
@@ -4380,6 +4483,25 @@
|
||||
qs('#retry-review-load').addEventListener('click', () => {
|
||||
if (selectedReview) openReviewSheet(selectedReview, reviewTrigger);
|
||||
});
|
||||
qs('#refresh-review-checks').addEventListener('click', async () => {
|
||||
if (!selectedReview || offlineReview) return;
|
||||
const item = selectedReview;
|
||||
const button = qs('#refresh-review-checks');
|
||||
button.disabled = true;
|
||||
qs('#review-checks-summary').textContent = 'Refreshing…';
|
||||
try {
|
||||
const detail = await reviewController.load(item);
|
||||
if (selectedReview !== item) return;
|
||||
if (selectedReviewHead && detail.head_sha !== selectedReviewHead) {
|
||||
qs('#review-sheet-status').textContent = 'New commits detected. Reload the review before submitting feedback.';
|
||||
qs('#submit-review').disabled = true;
|
||||
}
|
||||
qs('#review-ci-state').textContent = 'CI ' + (detail.ci_state || 'unknown');
|
||||
renderCheckSection('review', detail);
|
||||
} catch (error) {
|
||||
if (selectedReview === item) qs('#review-checks-summary').textContent = 'Refresh failed · retry';
|
||||
} finally { button.disabled = false; }
|
||||
});
|
||||
qs('#next-unreviewed-review').addEventListener('click', () => {
|
||||
if (progress) openNextUnreviewed(progress.snapshot());
|
||||
});
|
||||
|
||||
@@ -558,6 +558,15 @@
|
||||
<textarea id="pull-comment" maxlength="10000" placeholder="Write a comment"></textarea>
|
||||
<div class="mention-options" id="pull-comment-mentions" role="listbox" aria-label="Teammates" hidden></div>
|
||||
<div class="mention-status small" id="pull-comment-mention-status" aria-live="polite"></div>
|
||||
<div class="issue-attachment-controls">
|
||||
<input class="visually-hidden" id="pull-attachment" type="file" accept="image/png,image/jpeg,image/webp" />
|
||||
<label class="issue-attachment-trigger" for="pull-attachment">Attach screenshot</label>
|
||||
</div>
|
||||
<div class="issue-attachment-preview" id="pull-attachment-preview" hidden>
|
||||
<img id="pull-attachment-image" alt="Selected screenshot preview" />
|
||||
<span class="small" id="pull-attachment-meta"></span>
|
||||
<button id="remove-pull-attachment" type="button">Remove screenshot</button>
|
||||
</div>
|
||||
<div class="comment-actions">
|
||||
<button id="send-pull-comment" type="button">Post comment</button>
|
||||
<button id="send-pull-comment-next" type="button" hidden>Comment & next</button>
|
||||
@@ -569,6 +578,11 @@
|
||||
<div id="pull-review-status" class="small" aria-live="polite">Expand to load changed files and merge readiness.</div>
|
||||
<button class="pull-retry" id="pull-review-retry" type="button" hidden>Retry review data</button>
|
||||
<div class="row"><span class="pill" id="pull-ci-state">CI unknown</span><span class="pill" id="pull-merge-state">Review data not loaded</span></div>
|
||||
<details class="ci-checks" id="pull-checks">
|
||||
<summary><span>Checks</span><span class="small" id="pull-checks-summary">Not loaded</span></summary>
|
||||
<button class="ci-check-refresh" id="refresh-pull-checks" type="button">Refresh checks</button>
|
||||
<div class="ci-check-list" id="pull-check-list"></div>
|
||||
</details>
|
||||
<div class="pull-review-tools"><span id="pull-review-progress" class="small" aria-live="polite">Review progress unavailable.</span><button id="next-unreviewed-pull-file" type="button" disabled>Next unreviewed</button></div>
|
||||
<div id="pull-files"></div>
|
||||
<button id="merge-pull" type="button" disabled>Merge</button>
|
||||
@@ -600,6 +614,11 @@
|
||||
<button class="review-retry" id="retry-review-load" hidden>Retry loading review</button>
|
||||
<div class="review-sheet-body markdown-content" id="review-sheet-body"></div>
|
||||
<div class="row"><span class="pill" id="review-ci-state">CI unknown</span><button class="share-work-route" type="button">Share</button><a id="open-review-gitea" href="#" target="_blank" rel="noopener noreferrer">Open in Gitea</a></div>
|
||||
<details class="ci-checks" id="review-checks">
|
||||
<summary><span>Checks</span><span class="small" id="review-checks-summary">Not loaded</span></summary>
|
||||
<button class="ci-check-refresh" id="refresh-review-checks" type="button">Refresh checks</button>
|
||||
<div class="ci-check-list" id="review-check-list"></div>
|
||||
</details>
|
||||
<h2>Changed files</h2>
|
||||
<div class="review-display-tools">
|
||||
<button id="review-wrap-lines" type="button" aria-pressed="false" aria-controls="review-files">Wrap lines</button>
|
||||
|
||||
@@ -181,6 +181,11 @@
|
||||
let previewUrl = '';
|
||||
let selectionSequence = 0;
|
||||
|
||||
function setBusy(busy) {
|
||||
options.input.disabled = Boolean(busy);
|
||||
options.remove.disabled = Boolean(busy);
|
||||
}
|
||||
|
||||
function clearPreview() {
|
||||
selectionSequence += 1;
|
||||
if (previewUrl) options.revokeObjectURL(previewUrl);
|
||||
@@ -247,7 +252,7 @@
|
||||
return restored;
|
||||
}
|
||||
|
||||
return Object.assign(controller, { clear: clearPreview, restore: restorePreview });
|
||||
return Object.assign(controller, { clear: clearPreview, restore: restorePreview, setBusy });
|
||||
}
|
||||
|
||||
return { create, mount, multipart, optimizeImage, MAX_BYTES };
|
||||
|
||||
@@ -5,7 +5,11 @@ function mergeEligibility(detail, reviewState) {
|
||||
if (detail.draft) return { allowed: false, reason: 'Draft pull requests cannot be merged' };
|
||||
if (!detail.mergeable) return { allowed: false, reason: 'Resolve conflicts before merging' };
|
||||
if (detail.ci_state !== 'success') {
|
||||
return { allowed: false, reason: 'CI must succeed before merging' };
|
||||
const blockers = (detail.checks || []).filter(check =>
|
||||
['failure', 'error', 'pending'].includes(check.state)
|
||||
).map(check => check.name).filter(Boolean).slice(0, 3);
|
||||
return { allowed: false, reason: blockers.length ?
|
||||
'CI blocked by ' + blockers.join(', ') : 'CI must succeed before merging' };
|
||||
}
|
||||
if (!detail.head_sha) return { allowed: false, reason: 'Current head is unavailable' };
|
||||
if (reviewState && !reviewState.complete) {
|
||||
@@ -64,9 +68,9 @@ function createPullSheet({ fetchJson, storage, createConversationPager = globalT
|
||||
load(item) {
|
||||
return fetchJson(pathFor(item) + '/detail', { headers: { Accept: 'application/json' } });
|
||||
},
|
||||
loadReview(item, headSha) {
|
||||
loadReview(item, headSha, { refresh = false } = {}) {
|
||||
const key = item.repository + '#' + item.number + ':' + headSha;
|
||||
if (reviewCache.has(key)) return Promise.resolve(reviewCache.get(key));
|
||||
if (!refresh && reviewCache.has(key)) return Promise.resolve(reviewCache.get(key));
|
||||
if (reviewRequests.has(key)) return reviewRequests.get(key);
|
||||
const request = fetchJson(pathFor(item) + '/review-data', {
|
||||
headers: { Accept: 'application/json' },
|
||||
|
||||
@@ -355,6 +355,34 @@ function prepareMergeContinuation({ storage, item, headSha, reviewed, decision }
|
||||
return true;
|
||||
}
|
||||
|
||||
function renderChecks(checks, escapeHtml, { offline = false } = {}) {
|
||||
const rank = { error: 0, failure: 0, pending: 1, warning: 2, unknown: 2, success: 3 };
|
||||
const items = (Array.isArray(checks) ? checks : []).filter(check =>
|
||||
check && typeof check.name === 'string' && check.name
|
||||
).map((check, index) => ({ ...check, index })).sort((left, right) =>
|
||||
(rank[left.state] ?? 2) - (rank[right.state] ?? 2) || left.index - right.index
|
||||
);
|
||||
const failed = items.filter(check => ['failure', 'error'].includes(check.state)).length;
|
||||
const pending = items.filter(check => check.state === 'pending').length;
|
||||
const passed = items.filter(check => check.state === 'success').length;
|
||||
const other = items.length - failed - pending - passed;
|
||||
const parts = [
|
||||
failed ? failed + ' failed' : '', pending ? pending + ' pending' : '',
|
||||
passed ? passed + ' passed' : '', other ? other + ' other' : '',
|
||||
].filter(Boolean);
|
||||
const summary = (offline ? 'Last known · ' : '') + (parts.join(' · ') || 'No checks reported');
|
||||
const html = items.map(check => {
|
||||
const url = typeof check.url === 'string' ? check.url : '';
|
||||
const link = url ? '<a class="ci-check-link" href="' + escapeHtml(url) +
|
||||
'" target="_blank" rel="noopener noreferrer">Open job</a>' : '';
|
||||
return '<article class="ci-check ci-check-' + escapeHtml(check.state || 'unknown') + '">' +
|
||||
'<div class="ci-check-copy"><strong>' + escapeHtml(check.name) + '</strong>' +
|
||||
'<span class="small">' + escapeHtml(check.state || 'unknown') +
|
||||
(check.description ? ' · ' + escapeHtml(check.description) : '') + '</span></div>' + link + '</article>';
|
||||
}).join('');
|
||||
return { summary, html, expanded: failed > 0 };
|
||||
}
|
||||
|
||||
createReviewController.renderDiffFile = renderDiffFile;
|
||||
createReviewController.createWrapPreference = createWrapPreference;
|
||||
createReviewController.parseDiffLines = parseDiffLines;
|
||||
@@ -364,6 +392,7 @@ createReviewController.createDraft = createDraft;
|
||||
createReviewController.formatFeedback = formatFeedback;
|
||||
createReviewController.copyAndContinue = copyAndContinue;
|
||||
createReviewController.prepareMergeContinuation = prepareMergeContinuation;
|
||||
createReviewController.renderChecks = renderChecks;
|
||||
|
||||
if (typeof module !== 'undefined' && module.exports) {
|
||||
module.exports = createReviewController;
|
||||
|
||||
@@ -145,6 +145,7 @@
|
||||
const labels = {
|
||||
sign_in: 'Signed in',
|
||||
sign_out: 'Signed out',
|
||||
passkey_enrolled: 'Passkey enrolled',
|
||||
device_revoked: 'Device access revoked',
|
||||
all_sessions_revoked: 'All device access revoked',
|
||||
issue_closed: 'Issue closed',
|
||||
|
||||
+75
-1
@@ -4,7 +4,7 @@ import re
|
||||
import shlex
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
from urllib.parse import urljoin, urlsplit
|
||||
|
||||
import httpx
|
||||
|
||||
@@ -600,6 +600,51 @@ def _safe_web_url(value: Any) -> str:
|
||||
return value if parsed.scheme in {"http", "https"} and parsed.netloc else ""
|
||||
|
||||
|
||||
def _safe_gitea_web_url(value: Any) -> str:
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
return ""
|
||||
resolved = urljoin(f"{GITEA_URL}/", value.strip())
|
||||
parsed = urlsplit(resolved)
|
||||
configured = urlsplit(GITEA_URL)
|
||||
base_path = configured.path.rstrip("/")
|
||||
if (
|
||||
parsed.scheme not in {"http", "https"}
|
||||
or parsed.scheme != configured.scheme
|
||||
or parsed.netloc != configured.netloc
|
||||
or (base_path and parsed.path != base_path and not parsed.path.startswith(f"{base_path}/"))
|
||||
):
|
||||
return ""
|
||||
return resolved
|
||||
|
||||
|
||||
def _normalize_commit_checks(status: Any) -> list[dict]:
|
||||
entries = status.get("statuses") if isinstance(status, dict) else None
|
||||
if not isinstance(entries, list):
|
||||
return []
|
||||
rank = {"error": 0, "failure": 0, "pending": 1, "warning": 2, "success": 3}
|
||||
checks = []
|
||||
for index, entry in enumerate(entries):
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
name = entry.get("context")
|
||||
if not isinstance(name, str) or not name.strip():
|
||||
continue
|
||||
state = entry.get("status", entry.get("state", "unknown"))
|
||||
state = state.lower() if isinstance(state, str) else "unknown"
|
||||
if state not in rank:
|
||||
state = "unknown"
|
||||
description = entry.get("description")
|
||||
checks.append({
|
||||
"name": name.strip()[:120],
|
||||
"state": state,
|
||||
"description": description.strip()[:240] if isinstance(description, str) else "",
|
||||
"url": _safe_gitea_web_url(entry.get("target_url")),
|
||||
"_index": index,
|
||||
})
|
||||
checks.sort(key=lambda check: (rank.get(check["state"], 2), check["_index"]))
|
||||
return [{key: value for key, value in check.items() if key != "_index"} for check in checks[:20]]
|
||||
|
||||
|
||||
def _normalize_notifications(threads: Any) -> list[dict]:
|
||||
if not isinstance(threads, list):
|
||||
raise ValueError("Gitea notification response was not a list")
|
||||
@@ -920,6 +965,33 @@ async def upload_assigned_issue_attachment(
|
||||
return {"name": name, "url": url, "size": size}
|
||||
|
||||
|
||||
async def upload_assigned_pull_attachment(
|
||||
repository: str,
|
||||
number: int,
|
||||
filename: str,
|
||||
content_type: str,
|
||||
content: bytes,
|
||||
) -> dict:
|
||||
if not await is_assigned_pull(repository, number):
|
||||
raise IssueNotAvailableError("Assigned pull request not found")
|
||||
response = await _get_client().post(
|
||||
f"/api/v1/repos/{repository}/issues/{number}/assets",
|
||||
headers=_auth(),
|
||||
params={"name": filename},
|
||||
files={"attachment": (filename, content, content_type)},
|
||||
)
|
||||
response.raise_for_status()
|
||||
attachment = response.json()
|
||||
if not isinstance(attachment, dict):
|
||||
raise ValueError("Gitea attachment response was not an object")
|
||||
name = attachment.get("name")
|
||||
url = _safe_web_url(attachment.get("browser_download_url"))
|
||||
size = attachment.get("size")
|
||||
if not isinstance(name, str) or not name or not url or not isinstance(size, int):
|
||||
raise ValueError("Gitea did not confirm the attachment")
|
||||
return {"name": name, "url": url, "size": size}
|
||||
|
||||
|
||||
async def repo_labels(repository: str) -> list[dict]:
|
||||
response = await _get_client().get(
|
||||
f"/api/v1/repos/{repository}/labels",
|
||||
@@ -1714,6 +1786,7 @@ async def pull_completion_review(repository: str, number: int) -> dict:
|
||||
"mergeable": pull.get("mergeable") is True,
|
||||
"merged": pull.get("merged") is True,
|
||||
"ci_state": status.get("state", "unknown") if isinstance(status, dict) else "unknown",
|
||||
"checks": _normalize_commit_checks(status),
|
||||
"files": [
|
||||
{
|
||||
"filename": item.get("filename", ""),
|
||||
@@ -1846,6 +1919,7 @@ async def pull_review_detail(repository: str, number: int) -> dict:
|
||||
"author": user.get("login", ""),
|
||||
"head_sha": sha,
|
||||
"ci_state": status.get("state", "unknown") if isinstance(status, dict) else "unknown",
|
||||
"checks": _normalize_commit_checks(status),
|
||||
"files": normalized_files,
|
||||
"reviews": normalized_reviews,
|
||||
}
|
||||
|
||||
+90
-3
@@ -1158,6 +1158,24 @@ async def verify_passkey_registration(payload: PasskeyCeremony, request: Request
|
||||
)
|
||||
devices = await dashboard_auth.active_devices(request.state.dashboard_session)
|
||||
current = next(device for device in devices if device.current)
|
||||
except dashboard_auth.SessionStoreError:
|
||||
raise HTTPException(status_code=503, detail="Passkey registry is temporarily unavailable")
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=400, detail="Passkey verification failed") from exc
|
||||
journal = _security_event_store()
|
||||
try:
|
||||
operation_id = await asyncio.to_thread(
|
||||
journal.reserve,
|
||||
"passkey_enrolled",
|
||||
method="passkey",
|
||||
device_label=current.device_label,
|
||||
target="passkey",
|
||||
)
|
||||
except SecurityEventStoreError:
|
||||
raise HTTPException(
|
||||
status_code=503, detail="Security activity is temporarily unavailable"
|
||||
)
|
||||
try:
|
||||
await asyncio.to_thread(
|
||||
store.register,
|
||||
credential_id=verified.credential_id,
|
||||
@@ -1167,9 +1185,17 @@ async def verify_passkey_registration(payload: PasskeyCeremony, request: Request
|
||||
management_id=current.management_id,
|
||||
)
|
||||
except dashboard_auth.SessionStoreError:
|
||||
raise HTTPException(status_code=503, detail="Passkey registry is temporarily unavailable")
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=400, detail="Passkey verification failed") from exc
|
||||
try:
|
||||
await asyncio.to_thread(journal.discard, operation_id)
|
||||
except SecurityEventStoreError:
|
||||
pass
|
||||
raise HTTPException(
|
||||
status_code=503, detail="Passkey registry is temporarily unavailable"
|
||||
)
|
||||
try:
|
||||
await asyncio.to_thread(journal.finalize, operation_id)
|
||||
except SecurityEventStoreError:
|
||||
pass
|
||||
return JSONResponse(
|
||||
{"enrolled": True}, status_code=201, headers={"Cache-Control": "no-store"}
|
||||
)
|
||||
@@ -3442,6 +3468,67 @@ async def attach_to_assigned_issue(
|
||||
return JSONResponse(result, status_code=201)
|
||||
|
||||
|
||||
@app.post("/api/v1/repos/{owner}/{repo}/pulls/{number}/attachments", status_code=201)
|
||||
async def attach_to_assigned_pull(
|
||||
request: Request,
|
||||
owner: str,
|
||||
repo: str,
|
||||
number: int = PathParam(gt=0),
|
||||
idempotency_key: str | None = Header(default=None, max_length=128),
|
||||
):
|
||||
repository = f"{owner}/{repo}"
|
||||
try:
|
||||
if request.headers.get("content-type", "").lower().startswith("multipart/form-data"):
|
||||
form = await request.form()
|
||||
uploaded = form.get("file")
|
||||
if not isinstance(uploaded, UploadFile):
|
||||
raise ValueError("screenshot file is required")
|
||||
filename = str(uploaded.filename or "")
|
||||
content_type = str(uploaded.content_type or "")
|
||||
content = _validate_binary_attachment(filename, content_type, await uploaded.read())
|
||||
else:
|
||||
attachment = IssueAttachment.model_validate(await request.json())
|
||||
filename = attachment.filename
|
||||
content_type = attachment.content_type
|
||||
content = attachment.content()
|
||||
except (ValueError, ValidationError) as exc:
|
||||
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
||||
|
||||
async def upload_attachment():
|
||||
result = await gitea_proxy.upload_assigned_pull_attachment(
|
||||
repository, number, filename, content_type, content
|
||||
)
|
||||
safe_name = (
|
||||
result["name"].replace("\\", "\\\\").replace("[", "\\[").replace("]", "\\]")
|
||||
.replace("\r", " ").replace("\n", " ")
|
||||
)
|
||||
safe_url = result["url"].replace("<", "%3C").replace(">", "%3E")
|
||||
result["markdown"] = f""
|
||||
return result
|
||||
|
||||
try:
|
||||
result = await _run_idempotent_authored_action(
|
||||
upload_attachment(),
|
||||
idempotency_key=idempotency_key,
|
||||
fingerprint=(
|
||||
"pull-attachment", repository, number, filename, content_type,
|
||||
hashlib.sha256(content).hexdigest(),
|
||||
),
|
||||
timeout=ISSUE_ACTION_TIMEOUT_SECONDS,
|
||||
)
|
||||
except gitea_proxy.IssueNotAvailableError as exc:
|
||||
raise HTTPException(status_code=404, detail="Assigned pull request not found") from exc
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
return JSONResponse(
|
||||
{"error": "The screenshot could not be uploaded. Your draft is safe; please retry."},
|
||||
status_code=503,
|
||||
headers={"Retry-After": "1"},
|
||||
)
|
||||
return JSONResponse(result, status_code=201)
|
||||
|
||||
|
||||
@app.patch("/api/v1/repos/{owner}/{repo}/issues/{number}/close")
|
||||
async def close_assigned_issue(
|
||||
request: Request,
|
||||
|
||||
@@ -18,7 +18,7 @@ def request_body_limit(method: str, path: str) -> int | None:
|
||||
if (
|
||||
normalized_method == "POST"
|
||||
and path.startswith("/api/v1/repos/")
|
||||
and "/issues/" in path
|
||||
and ("/issues/" in path or "/pulls/" in path)
|
||||
and path.endswith("/attachments")
|
||||
):
|
||||
return ISSUE_ATTACHMENT_BODY_LIMIT
|
||||
|
||||
@@ -578,3 +578,29 @@ const outbox=createAuthoredOutbox({{storage,getOwnerLogin:()=>'timmy',background
|
||||
"""
|
||||
output = run_node(script)
|
||||
assert output == {"error": "IndexedDB unavailable", "items": []}
|
||||
|
||||
|
||||
def test_pull_screenshot_comment_persists_blob_only_in_indexeddb():
|
||||
script = f"""
|
||||
const createAuthoredOutbox=require({json.dumps(str(OUTBOX))});
|
||||
const values=new Map();const mirrors=[];
|
||||
const storage={{getItem:k=>values.get(k)||null,setItem:(k,v)=>values.set(k,v)}};
|
||||
const outbox=createAuthoredOutbox({{storage,getOwnerLogin:()=>'timmy',backgroundSync:{{
|
||||
reconcile:async items=>mirrors.push(items),requestSync:async()=>{{}},
|
||||
}}}});
|
||||
(async()=>{{const blob=new Blob(['PULL-PRIVATE-BYTES'],{{type:'image/webp'}});
|
||||
await outbox.enqueueDurably({{kind:'pull-comment',repository:'stackchain/web',number:31,
|
||||
body:'Mobile proof',operationId:'pull-image-31',
|
||||
attachment:{{filename:'proof.webp',contentType:'image/webp',blob}}}});
|
||||
const local=values.get('stackchain.authored-outbox.v1');const durable=mirrors[0][0].attachment;
|
||||
process.stdout.write(JSON.stringify({{local,metadata:JSON.parse(local).items[0].attachment,
|
||||
durable:{{isBlob:durable.blob instanceof Blob,text:await durable.blob.text()}}}}));
|
||||
}})();
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert "PULL-PRIVATE-BYTES" not in output["local"]
|
||||
assert output["metadata"] == {
|
||||
"filename": "proof.webp", "contentType": "image/webp", "stored": True
|
||||
}
|
||||
assert output["durable"] == {"isBlob": True, "text": "PULL-PRIVATE-BYTES"}
|
||||
@@ -237,6 +237,71 @@ const fetchJson=async(url,options={{}})=>{{
|
||||
assert output["second"]["confirmed"] == [{"id": 91}]
|
||||
|
||||
|
||||
def test_pull_screenshot_retry_uploads_to_pull_and_reuses_checkpoint_before_one_comment():
|
||||
script = f"""
|
||||
const createBackgroundIssueSync=require({json.dumps(str(SYNC))});
|
||||
let item={{id:'pull-image',operationId:'pull-image',ownerLogin:'timmy',status:'queued',
|
||||
kind:'pull-comment',repository:'stackchain/web',number:31,body:'Mobile proof',
|
||||
attachment:{{filename:'proof.png',contentType:'image/png',blob:new Blob(['proof'],{{type:'image/png'}})}}}};
|
||||
const calls=[];let commentAttempts=0;
|
||||
const store={{claimNext:async()=>item?{{...item}}:null,update:async(_id,fn)=>{{item=fn(item);}},
|
||||
complete:async()=>{{item=null;}},release:async()=>{{item={{...item,status:'queued'}};}},fail:async()=>{{}},countBlocked:async()=>0}};
|
||||
const fetchJson=async(url,options={{}})=>{{if(url==='api/v1/background-identity')return{{login:'timmy'}};
|
||||
calls.push({{url,key:options.headers?.['Idempotency-Key'],body:options.body instanceof FormData?'multipart':JSON.parse(options.body)}});
|
||||
if(url.endsWith('/attachments'))return{{markdown:''}};
|
||||
if(commentAttempts++===0){{const error=new Error('offline');error.status=503;throw error;}}return{{id:77}};
|
||||
}};
|
||||
(async()=>{{const sync=createBackgroundIssueSync({{store,fetchJson}});try{{await sync.flush();}}catch(_error){{}}
|
||||
const checkpoint=item.attachmentMarkdown;const result=await sync.flush();
|
||||
process.stdout.write(JSON.stringify({{calls,checkpoint,result}}));}})();
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert output["checkpoint"].startswith("![proof.png]")
|
||||
assert [call["url"] for call in output["calls"]] == [
|
||||
"api/v1/repos/stackchain/web/pulls/31/attachments",
|
||||
"api/v1/repos/stackchain/web/pulls/31/comments",
|
||||
"api/v1/repos/stackchain/web/pulls/31/comments",
|
||||
]
|
||||
assert [call["key"] for call in output["calls"]] == [
|
||||
"pull-image:attachment", "pull-image:comment", "pull-image:comment"
|
||||
]
|
||||
assert output["calls"][-1]["body"] == {
|
||||
"body": "Mobile proof\n\n"
|
||||
}
|
||||
assert output["result"]["confirmed"] == [{"id": 77}]
|
||||
|
||||
|
||||
def test_pull_screenshot_comment_timeout_replays_one_upload_with_durable_stage_identity():
|
||||
script = f"""
|
||||
const createBackgroundIssueSync=require({json.dumps(str(SYNC))});
|
||||
let item={{id:'pull-timeout',operationId:'pull-timeout',ownerLogin:'timmy',status:'queued',
|
||||
kind:'pull-comment',repository:'stackchain/web',number:31,body:'Mobile proof',
|
||||
attachment:{{filename:'proof.png',contentType:'image/png',blob:new Blob(['proof'],{{type:'image/png'}})}}}};
|
||||
const calls=[];let commentAttempts=0;
|
||||
const store={{claimNext:async()=>item?{{...item}}:null,update:async(_id,fn)=>{{item=fn(item);}},
|
||||
complete:async()=>{{item=null;}},release:async()=>{{item={{...item,status:'queued'}};}},fail:async()=>{{}},countBlocked:async()=>0}};
|
||||
const fetchJson=async(url,options={{}})=>{{if(url==='api/v1/background-identity')return{{login:'timmy'}};
|
||||
calls.push({{url,key:options.headers?.['Idempotency-Key']}});
|
||||
if(url.endsWith('/attachments'))return{{markdown:''}};
|
||||
if(commentAttempts++===0)return new Promise(()=>{{}});return{{id:78}};
|
||||
}};
|
||||
(async()=>{{const sync=createBackgroundIssueSync({{store,fetchJson,requestTimeoutMs:5}});
|
||||
let timedOut='';try{{await sync.flush();}}catch(error){{timedOut=error.message;}}
|
||||
const checkpoint=item.attachmentMarkdown;const replay=await sync.flush();
|
||||
process.stdout.write(JSON.stringify({{calls,timedOut,checkpoint,replay}}));}})();
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert output["timedOut"] == "Background request timed out."
|
||||
assert output["checkpoint"].startswith("![proof.png]")
|
||||
assert [call["key"] for call in output["calls"]] == [
|
||||
"pull-timeout:attachment", "pull-timeout:comment", "pull-timeout:comment"
|
||||
]
|
||||
assert sum(call["url"].endswith("/attachments") for call in output["calls"]) == 1
|
||||
assert output["replay"]["confirmed"] == [{"id": 78}]
|
||||
|
||||
|
||||
def test_closed_app_sync_retains_created_issue_for_create_and_start_recovery():
|
||||
script = f"""
|
||||
const createBackgroundIssueSync = require({json.dumps(str(SYNC))});
|
||||
|
||||
@@ -154,6 +154,15 @@ async def test_enrolled_passkey_can_sign_in_without_the_operator_token(
|
||||
"created_at": activity.json()["events"][0]["created_at"],
|
||||
"status": "completed",
|
||||
}
|
||||
assert activity.json()["events"][1] == {
|
||||
"id": activity.json()["events"][1]["id"],
|
||||
"kind": "passkey_enrolled",
|
||||
"method": "passkey",
|
||||
"device_label": "Phone",
|
||||
"target": "passkey",
|
||||
"created_at": activity.json()["events"][1]["created_at"],
|
||||
"status": "completed",
|
||||
}
|
||||
assert "stackchain_session=" in signed_in.headers["set-cookie"]
|
||||
assert "correct horse battery staple" not in signed_in.text
|
||||
|
||||
|
||||
@@ -655,6 +655,14 @@ def test_security_activity_explains_pending_outcome_confirmation():
|
||||
assert "event.status === 'pending'" in source
|
||||
|
||||
|
||||
def test_security_activity_labels_passkey_enrollment_without_html_rendering():
|
||||
source = SESSION_JS.read_text()
|
||||
|
||||
assert "passkey_enrolled: 'Passkey enrolled'" in source
|
||||
assert "title.textContent = labels[event.kind]" in source
|
||||
assert "details.textContent =" in source
|
||||
|
||||
|
||||
def test_security_activity_labels_consequential_pull_review_decisions():
|
||||
source = SESSION_JS.read_text()
|
||||
|
||||
|
||||
@@ -406,6 +406,28 @@ Promise.resolve(pending).then(async()=>process.stdout.write(JSON.stringify({{
|
||||
}
|
||||
|
||||
|
||||
def test_pending_comment_admission_locks_attachment_replacement_and_remove_controls():
|
||||
script = f"""
|
||||
const attachment=require({json.dumps(str(ATTACHMENT))});
|
||||
class Element {{
|
||||
constructor() {{ this.listeners={{}};this.hidden=true;this.value='';this.files=[];this.textContent='';this.src='';this.disabled=false; }}
|
||||
addEventListener(type,fn) {{ this.listeners[type]=fn; }}
|
||||
}}
|
||||
const input=new Element(),preview=new Element(),image=new Element(),meta=new Element(),remove=new Element(),status=new Element();
|
||||
const controller=attachment.mount({{input,preview,image,meta,remove,status,
|
||||
createObjectURL:()=> 'blob:preview',revokeObjectURL:()=>{{}},upload:async()=>{{}}}});
|
||||
controller.setBusy(true);
|
||||
const pending={{input:input.disabled,remove:remove.disabled}};
|
||||
controller.setBusy(false);
|
||||
process.stdout.write(JSON.stringify({{pending,released:{{input:input.disabled,remove:remove.disabled}}}}));
|
||||
"""
|
||||
|
||||
assert json.loads(run_node(script)) == {
|
||||
"pending": {"input": True, "remove": True},
|
||||
"released": {"input": False, "remove": False},
|
||||
}
|
||||
|
||||
|
||||
def test_issue_comment_actions_upload_binary_multipart_before_posting_and_clear_after_acceptance():
|
||||
source = DASHBOARD.read_text()
|
||||
|
||||
@@ -450,3 +472,50 @@ def test_issue_screenshot_comments_queue_serialized_bytes_before_clearing_or_adv
|
||||
assert "await authoredOutbox.enqueueDurably(message)" in source
|
||||
assert "await issueCommentNext.admit(item, message)" in source
|
||||
assert "navigator.onLine === false" in source
|
||||
|
||||
|
||||
def test_assigned_pull_composer_offers_screenshot_preview_remove_and_reuses_optimizer():
|
||||
html = INDEX.read_text()
|
||||
source = DASHBOARD.read_text()
|
||||
|
||||
assert 'id="pull-attachment"' in html
|
||||
assert 'accept="image/png,image/jpeg,image/webp"' in html
|
||||
assert 'for="pull-attachment"' in html
|
||||
assert 'id="pull-attachment-preview"' in html
|
||||
assert 'id="pull-attachment-image"' in html
|
||||
assert 'id="remove-pull-attachment"' in html
|
||||
assert "const pullAttachmentController = issueAttachment.mount({" in source
|
||||
assert "pullAttachmentController.clear();" in source
|
||||
|
||||
|
||||
def test_retrying_same_pull_load_preserves_screenshot_but_target_change_clears_it():
|
||||
source = DASHBOARD.read_text()
|
||||
open_body = source.split("async function openPullSheet(item, trigger, offlineDetail = null) {", 1)[1].split(
|
||||
"\n function closePullSheet", 1
|
||||
)[0]
|
||||
|
||||
assert "if (!sameWorkTarget(selectedPull, item)) pullAttachmentController.clear();" in open_body
|
||||
|
||||
|
||||
def test_pull_screenshot_comment_uploads_or_durably_admits_before_clearing_draft():
|
||||
source = DASHBOARD.read_text()
|
||||
|
||||
assert "async function queuePullScreenshotComment" in source
|
||||
assert "attachment: await pullAttachmentController.serialize()" in source
|
||||
assert "await authoredOutbox.enqueueDurably(message)" in source
|
||||
assert "navigator.onLine === false" in source
|
||||
assert "Your comment and screenshot are safe; retry." in source
|
||||
|
||||
|
||||
def test_pull_screenshot_foreground_and_replay_share_the_durable_operation_pipeline():
|
||||
source = DASHBOARD.read_text()
|
||||
standard = source.split(
|
||||
"qs('#send-pull-comment').addEventListener('click', async () => {", 1
|
||||
)[1].split("\n });", 1)[0]
|
||||
comment_next = source.split("async function submitCommentAndNext(kind) {", 1)[1].split(
|
||||
"\n }\n qs('#send-issue-comment-next')", 1
|
||||
)[0]
|
||||
|
||||
assert "await queuePullScreenshotComment(item, body, operationId, false, true)" in standard
|
||||
assert "pullAttachmentController.prepareComment" not in standard
|
||||
assert "attachmentController.state() && (kind === 'pull' || navigator.onLine === false)" in comment_next
|
||||
@@ -402,3 +402,73 @@ async def test_attachment_endpoint_rejects_unsafe_or_mismatched_filename(monkeyp
|
||||
|
||||
assert [traversal.status_code, mismatch.status_code] == [422, 422]
|
||||
assert called is False
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_pull_attachment_endpoint_uploads_binary_to_exact_assigned_pull(monkeypatch):
|
||||
calls = []
|
||||
|
||||
async def upload(repository, number, filename, content_type, content):
|
||||
calls.append((repository, number, filename, content_type, content))
|
||||
return {
|
||||
"name": filename,
|
||||
"url": "https://forge.example/attachments/pull.png",
|
||||
"size": len(content),
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
main.gitea_proxy, "upload_assigned_pull_attachment", upload, raising=False
|
||||
)
|
||||
transport = httpx.ASGITransport(app=main.app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
response = await client.post(
|
||||
"/api/v1/repos/stackchain/web/pulls/31/attachments",
|
||||
files={"file": ("pull.png", PNG_BYTES, "image/png")},
|
||||
headers={"Idempotency-Key": "pull-image-31:attachment"},
|
||||
)
|
||||
replay = await client.post(
|
||||
"/api/v1/repos/stackchain/web/pulls/31/attachments",
|
||||
files={"file": ("pull.png", PNG_BYTES, "image/png")},
|
||||
headers={"Idempotency-Key": "pull-image-31:attachment"},
|
||||
)
|
||||
|
||||
assert response.status_code == replay.status_code == 201
|
||||
assert replay.json() == response.json()
|
||||
assert response.json()["markdown"] == (
|
||||
""
|
||||
)
|
||||
assert calls == [("stackchain/web", 31, "pull.png", "image/png", PNG_BYTES)]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_gitea_pull_attachment_revalidates_assignment_before_exact_pull_upload():
|
||||
requests = []
|
||||
|
||||
async def handler(request):
|
||||
requests.append(request)
|
||||
if request.url.path == "/api/v1/user":
|
||||
return httpx.Response(200, json={"login": "timmy"})
|
||||
if request.method == "GET":
|
||||
return httpx.Response(200, json={
|
||||
"state": "open", "assignees": [{"login": "timmy"}],
|
||||
})
|
||||
return httpx.Response(201, json={
|
||||
"name": "pull.png", "size": len(PNG_BYTES),
|
||||
"browser_download_url": "https://forge.example/attachments/pull.png",
|
||||
})
|
||||
|
||||
gitea_proxy.start_client(transport=httpx.MockTransport(handler))
|
||||
try:
|
||||
result = await gitea_proxy.upload_assigned_pull_attachment(
|
||||
"stackchain/web", 31, "pull.png", "image/png", PNG_BYTES
|
||||
)
|
||||
finally:
|
||||
await gitea_proxy.stop_client()
|
||||
|
||||
assert [(request.method, request.url.path) for request in requests] == [
|
||||
("GET", "/api/v1/user"),
|
||||
("GET", "/api/v1/repos/stackchain/web/pulls/31"),
|
||||
("POST", "/api/v1/repos/stackchain/web/issues/31/assets"),
|
||||
]
|
||||
assert PNG_BYTES in requests[-1].content
|
||||
assert result["url"] == "https://forge.example/attachments/pull.png"
|
||||
+76
-2
@@ -3965,7 +3965,9 @@ const createPullSheet = require({json.dumps(str(PULL_SHEET))});
|
||||
const states = [
|
||||
{{state:'open', draft:false, mergeable:true, merged:false, ci_state:'success', head_sha:'abc'}},
|
||||
{{state:'open', draft:true, mergeable:true, merged:false, ci_state:'success', head_sha:'abc'}},
|
||||
{{state:'open', draft:false, mergeable:true, merged:false, ci_state:'failure', head_sha:'abc'}},
|
||||
{{state:'open', draft:false, mergeable:true, merged:false, ci_state:'failure', head_sha:'abc', checks:[
|
||||
{{name:'lint', state:'failure'}}, {{name:'release', state:'pending'}}, {{name:'build', state:'success'}}
|
||||
]}},
|
||||
{{state:'open', draft:false, mergeable:false, merged:false, ci_state:'success', head_sha:'abc'}},
|
||||
];
|
||||
process.stdout.write(JSON.stringify(states.map(createPullSheet.mergeEligibility)));
|
||||
@@ -3974,7 +3976,7 @@ process.stdout.write(JSON.stringify(states.map(createPullSheet.mergeEligibility)
|
||||
output = json.loads(result.stdout)
|
||||
assert output[0] == {"allowed": True, "reason": "Ready to merge"}
|
||||
assert output[1]["allowed"] is False and "draft" in output[1]["reason"].lower()
|
||||
assert output[2]["allowed"] is False and "CI" in output[2]["reason"]
|
||||
assert output[2] == {"allowed": False, "reason": "CI blocked by lint, release"}
|
||||
assert output[3]["allowed"] is False and "conflict" in output[3]["reason"].lower()
|
||||
|
||||
|
||||
@@ -4053,6 +4055,34 @@ Promise.allSettled([first, concurrent]).then(async failed => {{
|
||||
]
|
||||
|
||||
|
||||
def test_pull_sheet_refreshes_checks_without_clearing_head_scoped_progress():
|
||||
script = f"""
|
||||
const createPullSheet = require({json.dumps(str(PULL_SHEET))});
|
||||
const values = new Map();
|
||||
const storage = {{getItem:k => values.get(k) || null, setItem:(k,v) => values.set(k,v)}};
|
||||
const calls = [];
|
||||
const sheet = createPullSheet({{storage, fetchJson: url => {{
|
||||
calls.push(url);
|
||||
return Promise.resolve({{head_sha:'abc123', ci_state:calls.length === 1 ? 'pending' : 'success',
|
||||
checks:[{{name:'lint', state:calls.length === 1 ? 'pending' : 'success'}}],
|
||||
files:[{{filename:'src/api.py'}}]}});
|
||||
}}}});
|
||||
const item = {{repository:'stackchain/api', number:7}};
|
||||
sheet.loadReview(item, 'abc123').then(first => {{
|
||||
sheet.toggleReviewed(item, first, 'src/api.py');
|
||||
return sheet.loadReview(item, 'abc123', {{refresh:true}}).then(refreshed => {{
|
||||
process.stdout.write(JSON.stringify({{calls, refreshed, progress:sheet.reviewState(item, refreshed)}}));
|
||||
}});
|
||||
}});
|
||||
"""
|
||||
result = subprocess.run(["node", "-e", script], check=True, capture_output=True, text=True)
|
||||
output = json.loads(result.stdout)
|
||||
|
||||
assert len(output["calls"]) == 2
|
||||
assert output["refreshed"]["ci_state"] == "success"
|
||||
assert output["progress"] == {"reviewed": ["src/api.py"], "total": 1, "complete": True}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_mobile_pull_sheet_puts_reading_before_collapsed_review_controls():
|
||||
html = await dashboard()
|
||||
@@ -4493,6 +4523,50 @@ process.stdout.write(JSON.stringify({{ html, expanded: button.attrs['aria-expand
|
||||
assert output["hidden"] is False
|
||||
|
||||
|
||||
def test_review_checks_render_blockers_first_with_safe_touch_links():
|
||||
script = f"""
|
||||
const reviewSheet = require({json.dumps(str(REVIEW_SHEET))});
|
||||
const escapeHtml = value => String(value)
|
||||
.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"');
|
||||
const result = reviewSheet.renderChecks([
|
||||
{{name:'build', state:'success', description:'Passed'}},
|
||||
{{name:'lint <mobile>', state:'failure', description:'Open & fix', url:'https://forge.example/jobs/4'}},
|
||||
{{name:'release', state:'pending', description:'Waiting'}},
|
||||
], escapeHtml, {{offline:false}});
|
||||
const offline = reviewSheet.renderChecks([
|
||||
{{name:'lint', state:'success', description:'Passed'}},
|
||||
], escapeHtml, {{offline:true}});
|
||||
process.stdout.write(JSON.stringify({{result, offline}}));
|
||||
"""
|
||||
result = subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
)
|
||||
output = json.loads(result.stdout)
|
||||
|
||||
assert output["result"]["summary"] == "1 failed · 1 pending · 1 passed"
|
||||
assert output["result"]["expanded"] is True
|
||||
assert output["result"]["html"].index("lint <mobile>") < output["result"]["html"].index("build")
|
||||
assert 'href="https://forge.example/jobs/4"' in output["result"]["html"]
|
||||
assert 'target="_blank" rel="noopener noreferrer"' in output["result"]["html"]
|
||||
assert "Open job" in output["result"]["html"]
|
||||
assert output["offline"]["summary"].startswith("Last known · ")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_mobile_pull_review_sheets_expose_actionable_refreshable_checks():
|
||||
html = await dashboard()
|
||||
|
||||
assert html.index('id="pull-checks"') < html.index('id="pull-files"')
|
||||
assert html.index('id="review-checks"') < html.index('id="review-files"')
|
||||
assert 'id="refresh-pull-checks"' in html
|
||||
assert 'id="refresh-review-checks"' in html
|
||||
assert "createReviewController.renderChecks" in html
|
||||
assert "{ refresh: true }" in html
|
||||
assert "qs('#refresh-review-checks').disabled = offlineReview" in html
|
||||
assert ".ci-check-link" in html and "min-height:44px" in html
|
||||
assert ".ci-check-copy" in html and "overflow-wrap:anywhere" in html
|
||||
|
||||
|
||||
def test_review_wrap_preference_defaults_to_phone_layout_and_persists_explicit_choice():
|
||||
script = f"""
|
||||
const reviewSheet = require({json.dumps(str(REVIEW_SHEET))});
|
||||
|
||||
@@ -122,6 +122,15 @@ def test_request_limits_are_route_specific_and_cover_api_mutations():
|
||||
assert main.request_body_limit("POST", "/unrelated") is None
|
||||
|
||||
|
||||
def test_pull_screenshot_upload_uses_binary_attachment_boundary():
|
||||
assert (
|
||||
main.request_body_limit(
|
||||
"POST", "/api/v1/repos/stackchain/project/pulls/31/attachments"
|
||||
)
|
||||
== 2 * 1024 * 1024 + 64 * 1024
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_request_limit_uses_application_path_under_domain_subpath():
|
||||
downstream_called = False
|
||||
|
||||
@@ -36,6 +36,57 @@ async def test_review_detail_endpoint_returns_normalized_no_store_payload(monkey
|
||||
assert response.json()["files"][0]["filename"] == "src/api.py"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_gitea_review_detail_returns_bounded_actionable_checks(monkeypatch):
|
||||
monkeypatch.setattr(gitea_proxy, "GITEA_URL", "https://forge.example/git")
|
||||
|
||||
async def handler(request):
|
||||
path = request.url.path
|
||||
if path.endswith("/pulls/7"):
|
||||
return httpx.Response(200, json={
|
||||
"title": "Review API", "head": {"sha": "abc123"},
|
||||
"user": {"login": "alex"},
|
||||
})
|
||||
if path.endswith("/pulls/7/files") or path.endswith("/pulls/7/reviews"):
|
||||
return httpx.Response(200, json=[])
|
||||
if path.endswith("/commits/abc123/status"):
|
||||
return httpx.Response(200, json={
|
||||
"state": "failure",
|
||||
"statuses": [
|
||||
{
|
||||
"context": "lint/<unsafe>", "status": "failure",
|
||||
"description": "Formatting failed " + "x" * 300,
|
||||
"target_url": "https://forge.example/git/stackchain/api/actions/runs/9/jobs/4",
|
||||
},
|
||||
{
|
||||
"context": "external", "status": "pending",
|
||||
"description": "Waiting", "target_url": "https://evil.example/job/1",
|
||||
},
|
||||
{"context": "build-release", "status": "success", "description": "Passed"},
|
||||
] + [{"context": f"extra-{index}", "status": "success"} for index in range(30)],
|
||||
})
|
||||
if path.endswith("/pulls/7.diff"):
|
||||
return httpx.Response(200, text="")
|
||||
raise AssertionError(f"unexpected request: {request.method} {path}")
|
||||
|
||||
gitea_proxy.start_client(transport=httpx.MockTransport(handler))
|
||||
try:
|
||||
detail = await gitea_proxy.pull_review_detail("stackchain/api", 7)
|
||||
finally:
|
||||
await gitea_proxy.stop_client()
|
||||
|
||||
assert len(detail["checks"]) == 20
|
||||
assert detail["checks"][:3] == [
|
||||
{
|
||||
"name": "lint/<unsafe>", "state": "failure",
|
||||
"description": "Formatting failed " + "x" * 222,
|
||||
"url": "https://forge.example/git/stackchain/api/actions/runs/9/jobs/4",
|
||||
},
|
||||
{"name": "external", "state": "pending", "description": "Waiting", "url": ""},
|
||||
{"name": "build-release", "state": "success", "description": "Passed", "url": ""},
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_review_detail_rejects_pulls_not_requested_from_service_user(monkeypatch):
|
||||
async def requested(repository, number):
|
||||
|
||||
@@ -75,6 +75,172 @@ async def test_security_activity_limit_is_validated(security_access):
|
||||
assert invalid_cursor.status_code == 422
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_passkey_enrollment_reservation_failure_preserves_registry(
|
||||
security_access, monkeypatch
|
||||
):
|
||||
class VerifiedRegistration:
|
||||
credential_id = b"phone-credential"
|
||||
credential_public_key = b"credential-public-key"
|
||||
sign_count = 0
|
||||
|
||||
class UnavailableJournal:
|
||||
def reserve(self, *_args, **_kwargs):
|
||||
raise SecurityEventStoreError("unavailable")
|
||||
|
||||
monkeypatch.setattr(
|
||||
main.passkeys, "verify_registration", lambda **_kwargs: VerifiedRegistration()
|
||||
)
|
||||
transport = httpx.ASGITransport(app=main.app, raise_app_exceptions=False)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="https://test") as client:
|
||||
await client.post(
|
||||
"/api/v1/session",
|
||||
json={"access_token": "correct horse battery staple", "device_label": "Phone"},
|
||||
)
|
||||
headers = {
|
||||
"Origin": "https://test",
|
||||
"X-CSRF-Token": client.cookies["stackchain_csrf"],
|
||||
}
|
||||
grant = await client.post(
|
||||
"/api/v1/fresh-authorization",
|
||||
json={
|
||||
"access_token": "correct horse battery staple",
|
||||
"action": "enroll_passkey",
|
||||
"target": "current_device",
|
||||
},
|
||||
headers=headers,
|
||||
)
|
||||
options = await client.post(
|
||||
"/api/v1/passkeys/registration/options",
|
||||
headers={**headers, "X-Step-Up-Grant": grant.json()["grant"]},
|
||||
)
|
||||
monkeypatch.setattr(main, "_security_event_store", lambda: UnavailableJournal())
|
||||
enrolled = await client.post(
|
||||
"/api/v1/passkeys/registration/verify",
|
||||
json={"challenge": options.json()["challenge"], "credential": {"id": "fake"}},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
assert enrolled.status_code == 503
|
||||
assert enrolled.json() == {"detail": "Security activity is temporarily unavailable"}
|
||||
assert main._passkey_store().all() == []
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_passkey_enrollment_registry_failure_discards_reserved_event(
|
||||
security_access, monkeypatch
|
||||
):
|
||||
class VerifiedRegistration:
|
||||
credential_id = b"phone-credential"
|
||||
credential_public_key = b"credential-public-key"
|
||||
sign_count = 0
|
||||
|
||||
monkeypatch.setattr(
|
||||
main.passkeys, "verify_registration", lambda **_kwargs: VerifiedRegistration()
|
||||
)
|
||||
transport = httpx.ASGITransport(app=main.app, raise_app_exceptions=False)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="https://test") as client:
|
||||
await client.post(
|
||||
"/api/v1/session",
|
||||
json={"access_token": "correct horse battery staple", "device_label": "Phone"},
|
||||
)
|
||||
headers = {
|
||||
"Origin": "https://test",
|
||||
"X-CSRF-Token": client.cookies["stackchain_csrf"],
|
||||
}
|
||||
grant = await client.post(
|
||||
"/api/v1/fresh-authorization",
|
||||
json={
|
||||
"access_token": "correct horse battery staple",
|
||||
"action": "enroll_passkey",
|
||||
"target": "current_device",
|
||||
},
|
||||
headers=headers,
|
||||
)
|
||||
options = await client.post(
|
||||
"/api/v1/passkeys/registration/options",
|
||||
headers={**headers, "X-Step-Up-Grant": grant.json()["grant"]},
|
||||
)
|
||||
store = main._passkey_store()
|
||||
|
||||
def fail_registration(**_kwargs):
|
||||
raise main.dashboard_auth.SessionStoreError("unavailable")
|
||||
|
||||
monkeypatch.setattr(store, "register", fail_registration)
|
||||
monkeypatch.setattr(main, "_passkey_store", lambda: store)
|
||||
enrolled = await client.post(
|
||||
"/api/v1/passkeys/registration/verify",
|
||||
json={"challenge": options.json()["challenge"], "credential": {"id": "fake"}},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
events = SecurityEventStore(
|
||||
security_access / "security.sqlite3", clock=lambda: 0
|
||||
).list(limit=10).events
|
||||
assert enrolled.status_code == 503
|
||||
assert enrolled.json() == {"detail": "Passkey registry is temporarily unavailable"}
|
||||
assert all(event.kind != "passkey_enrolled" for event in events)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_passkey_enrollment_finalization_failure_retains_pending_event(
|
||||
security_access, monkeypatch
|
||||
):
|
||||
class VerifiedRegistration:
|
||||
credential_id = b"phone-credential"
|
||||
credential_public_key = b"credential-public-key"
|
||||
sign_count = 0
|
||||
|
||||
monkeypatch.setattr(
|
||||
main.passkeys, "verify_registration", lambda **_kwargs: VerifiedRegistration()
|
||||
)
|
||||
transport = httpx.ASGITransport(app=main.app, raise_app_exceptions=False)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="https://test") as client:
|
||||
await client.post(
|
||||
"/api/v1/session",
|
||||
json={"access_token": "correct horse battery staple", "device_label": "Phone"},
|
||||
)
|
||||
headers = {
|
||||
"Origin": "https://test",
|
||||
"X-CSRF-Token": client.cookies["stackchain_csrf"],
|
||||
}
|
||||
grant = await client.post(
|
||||
"/api/v1/fresh-authorization",
|
||||
json={
|
||||
"access_token": "correct horse battery staple",
|
||||
"action": "enroll_passkey",
|
||||
"target": "current_device",
|
||||
},
|
||||
headers=headers,
|
||||
)
|
||||
options = await client.post(
|
||||
"/api/v1/passkeys/registration/options",
|
||||
headers={**headers, "X-Step-Up-Grant": grant.json()["grant"]},
|
||||
)
|
||||
journal = main._security_event_store()
|
||||
|
||||
def fail_finalization(_operation_id):
|
||||
raise SecurityEventStoreError("unavailable")
|
||||
|
||||
monkeypatch.setattr(journal, "finalize", fail_finalization)
|
||||
monkeypatch.setattr(main, "_security_event_store", lambda: journal)
|
||||
enrolled = await client.post(
|
||||
"/api/v1/passkeys/registration/verify",
|
||||
json={"challenge": options.json()["challenge"], "credential": {"id": "fake"}},
|
||||
headers=headers,
|
||||
)
|
||||
activity = await client.get("/api/v1/security-events")
|
||||
|
||||
event = activity.json()["events"][0]
|
||||
assert enrolled.status_code == 201
|
||||
assert enrolled.json() == {"enrolled": True}
|
||||
assert event["kind"] == "passkey_enrolled"
|
||||
assert event["status"] == "pending"
|
||||
assert event["device_label"] == "Phone"
|
||||
assert event["method"] == "passkey"
|
||||
assert event["target"] == "passkey"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_revoked_device_activity_survives_live_session_removal(security_access):
|
||||
transport = httpx.ASGITransport(app=main.app)
|
||||
|
||||
Reference in new issue
Block a user